How C ++ constructor constructors are called when used with for_each or std :: transform

I have never used C ++ functions before, and so I'm just trying to figure out how they work.

eg. suppose we have this class of functors

class MultiplyBy { private: int factor; public: MultiplyBy(int x) : factor(x) { } int operator () (int other) const { return factor * other; } }; 

Using this as it is clear to me:

 MultiplyBy mult_3(3); int x = mult_3(100); 

The Obviosuly constructor of the MultiplyBy is invoked with argument 3.

But in the following case, how is a constructor called with a value in an array?

 int array[5] = {1, 2, 3, 4, 5}; std::transform(array, array + 5, array, MultiplyBy(3)); 
+3
source share
3 answers

You may think that the transformation is structured as follows:

 void transform(Iterator b, Iterator e, Functor f) { for(;b != e; ++b) { *b = f(*b); } } 

The functor is passed by value to the function.
Therefore, when you call it like this:

 std::transform(array, array + 5, array, MultiplyBy(3)); 

Here you have created a temporary object. This is passed as the parameter value to transfer (). This leads to the fact that the functor is copied to the function (not a problem, since it has only a POD element and the copy constructor generated by the compiler works fine). This parameter can be used normally.

Note. A temporary object is destroyed at the end of the expression that it was created (which will be returned after the conversion ()).

+3
source

Well, in the latter case, you create a new MultiplyBy object with 3 as the constructor argument. This object is then passed to std::transform , then it calls operator() on.

If this helps you better understand, this is identical:

 int array[] = {1, 2, 3, 4, 5}; MultiplyBy times3(3); std::transform(array, array + 5, array, times3); 
+3
source

MultiplyBy(3) creates an unnamed temporary variable that goes into transform and (at this point), taking into account the corresponding parameter name in this function.

+1
source

All Articles