Ego*_*gon 2 c++ stl functor function-object
引自NM Jousttis的"The C++ Standard Library",第5.9节
#include < iostream>
#include < list>
#include < algorithm>
using namespace std;
//function object that adds the value with which it is initialized
class AddValue {
private:
int the Value; //the value to add
public:
//constructor initializes the value to add
AddValue(int v) : theValue(v) { }
//the "function call" for the element adds the value
void operator() (int& elem) const { elem += theValue; }
};
int main()
{
list<int> coll;
for (int i=1; i<=9; ++i)
coll.push_back(i);
//The first call of for_each() adds 10 to each value:
for_each (coll.begin(), coll.end(), AddValue(10)) ;
Run Code Online (Sandbox Code Playgroud)
这里,表达式AddValue(10)创建一个AddValue类型的对象,该对象使用值10初始化.AddValue的构造函数将此值存储为成员theValue.在for_each()中,为coll的每个元素调用"()".同样,这是对传递的AddValue类型的临时函数对象的operator()调用.实际元素作为参数传递.函数对象将其值10添加到每个元素.然后元素具有以下值:添加10后:
11 12 13 14 15 16 17 18 19
Run Code Online (Sandbox Code Playgroud)
for_each()的第二次调用使用相同的功能将第一个元素的值添加到每个元素.它使用集合的第一个元素初始化AddValue类型的临时函数对象:
for_each (coll.begin(), coll.end(), AddValue (*coll. begin()) ) ;
Run Code Online (Sandbox Code Playgroud)
添加第一个元素后,输出如下:
22 23 24 25 26 27 28 29 30
Run Code Online (Sandbox Code Playgroud)
我不明白的是在第二种情况下为什么输出不是
22 34 35 36 37 38 39 40 41
Run Code Online (Sandbox Code Playgroud)
意思是为每个调用创建一个新的函子,还是每个调用使用的函子?
该表达式AddValue(*coll. begin())创建一个类的临时对象AddValue.然后将该临时值传递给for_each函数.for_each然后调用该对象的函数调用操作-也就是operator()-一旦从每个元素coll.begin()到coll.end().
从技术上讲,for_each通过值(不是引用)获取functor参数,因此它实际上在临时的副本上操作,而不是临时本身.