简体   繁体   English

与 for_each 或 std::transform 一起使用时如何调用 C++ 仿函数构造函数

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

I've never used c++ functors before and so I'm just trying to understand how they work.我以前从未使用过 c++ 仿函数,所以我只是想了解它们是如何工作的。

eg suppose we have this functor class例如假设我们有这个函子 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.显然 MultiplyBy 的构造函数是用参数 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));

Well, in the final case, you are creating a new MultiplyBy object with 3 as the constructor argument.好吧,在最后一种情况下,您将创建一个新的MultiplyBy object,其中 3 作为构造函数参数。 This object is then passed into std::transform , that it then calls operator() on.然后将此 object 传递给std::transform ,然后调用operator()

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);

You can think of transform being structured like this:您可以认为 transform 的结构如下:

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

The functor is passed by value into the function.函子按值传递给 function。
So when you call like this:所以当你这样打电话时:

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

Here you have created a temporary object.在这里,您创建了一个临时 object。 This is passed as a parameter value into transfer().这作为参数值传递给 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).这导致仿函数被复制到 function 中(这不是问题,因为它只有一个 POD 成员并且编译器生成的复制构造函数工作得很好)。 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).注意:临时 object 在创建它的表达式的末尾被销毁(这将在 transform() 返回之后)。

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. MultiplyBy(3)创建了一个未命名的临时变量,该变量将传递给transform并(此时)在 function 中给出相应的参数名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM