与for_each或std :: transform一起使用时,如何调用C ++函子构造函数 [英] How do C++ functor constructors get called when used with for_each or std::transform

查看:72
本文介绍了与for_each或std :: transform一起使用时,如何调用C ++函子构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前从未使用过c ++仿函数,所以我只是想了解它们的工作原理.

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

很显然,MultiplyBy的构造函数是使用参数3调用的.

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

推荐答案

您可以想到这样构造转换:

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

您在此处创建了一个临时对象.这作为参数值传递到transfer()中.这导致函子被复制到函数中(这不是问题,因为它只有一个POD成员,并且编译器生成的复制构造函数可以正常工作).该参数即可正常使用.

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.

注意:临时对象在创建它的表达式的末尾被破坏(将在transform()返回之后).

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

这篇关于与for_each或std :: transform一起使用时,如何调用C ++函子构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆