C++ 如何与 for_each 或 std::transform 一起使用时,函子构造函数会被调用
我以前从未使用过 C++ 函子,所以我只是想了解它们是如何工作的。
例如,假设我们有这个函子类,
class MultiplyBy {
private:
int factor;
public:
MultiplyBy(int x) : factor(x) { }
int operator () (int other) const {
return factor * other;
}
};
这样使用它对我来说很清楚:
MultiplyBy mult_3(3);
int x = mult_3(100);
显然,MultiplyBy 的构造函数是用参数 3 调用的。
但是在下面的情况下,如何用数组中的值调用构造函数?
int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
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));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,在最后一种情况下,您将创建一个新的 MultiplyBy 对象,并将 3 作为构造函数参数。然后,该对象被传递到 std::transform,然后调用
operator()
。如果它可以帮助您更好地理解,那么这是相同的:
Well, in the final case, you are creating a new
MultiplyBy
object with 3 as the constructor argument. This object is then passed intostd::transform
, that it then callsoperator()
on.If it helps you understand better, this is identical:
您可以将转换视为如下结构:
函子按值传递到函数中。
所以当你这样调用时:
这里你已经创建了一个临时对象。这作为参数值传递到transfer()。这会导致仿函数被复制到函数中(这不是问题,因为它只有一个 POD 成员,并且编译器生成的复制构造函数工作得很好)。然后该参数就可以正常使用了。
注意:临时对象在创建它的表达式末尾被销毁(将在transform()返回之后)。
You can think of transform being structured like this:
The functor is passed by value into the function.
So when you call like this:
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).
MultiplyBy(3)
创建一个未命名临时变量,该变量传递给transform
并(此时)给出该函数中参数的相应名称。MultiplyBy(3)
creates an unnamed temporary variable that's pass intotransform
and (at that point) given the corresponding name of the parameter in that function.