How do C++ functor constructors get called when used with for_each or std::transform

牧云@^-^@ 提交于 2019-12-07 18:14:41

问题


I've never used c++ functors before and so I'm just trying to understand how they work.

e.g. suppose we have this functor class

class MultiplyBy {
private:
    int factor;

public:
    MultiplyBy(int x) : factor(x) { }

    int operator () (int other) const {
        return factor * other;
    }
};

Using it like this is clear to me:

MultiplyBy mult_3(3);

int x = mult_3(100);

Obviosuly the constructor of MultiplyBy is being called with the argument 3.

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

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

回答1:


You can think of transform being structured like this:

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

The functor is passed by value into the function.
So when you call like this:

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

Here you have created a temporary object. This is passed as a parameter value into transfer(). This results in the functor being copied into the function (not a problem since it has only a POD member and the compiler generated copy constructor works just fine). The parameter can then be used normally.

Note: The temporary object is destroyed at the end of the expression that it was created in (which will be after transform() returns).




回答2:


Well, in the final case, you are creating a new MultiplyBy object with 3 as the constructor argument. This object is then passed into std::transform, that it then calls operator() on.

If it helps you understand better, this is identical:

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



回答3:


MultiplyBy(3) creates an unnamed temporary variable that's pass into transform and (at that point) given the corresponding name of the parameter in that function.



来源:https://stackoverflow.com/questions/6756532/how-do-c-functor-constructors-get-called-when-used-with-for-each-or-stdtrans

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!