概念
Function object首先是一个类,它实现了函数调用操作符T operator()(T), T可以是void类型。
最简单的示例:for_each
class A{
public:
A():x_(0){
}
void operator()(int x){
cout<<++x_<<endl;
}
int x() const{
return x_;
}
private:
int x_;
};
/*
*
*/
int main(int argc, char** argv) {
vector<int> v;
v.push_back(1);
v.push_back(2);
A a;
for_each(v.begin(),v.end(),a);
cout<<a.x()<<endl;
return 0;
}
输出结果是:
1
2
0
for_each的实现
通过查看for_each的源代码,可以观察到stl中使用function object的基本特征。下面是gcc4.6.1的实现代码:
/**
* @brief Apply a function to every element of a sequence.
* @ingroup non_mutating_algorithms
* @param first An input iterator.
* @param last An input iterator.
* @param f A unary function object.
* @return @p f (std::move(@p f) in C++0x).
*
* Applies the function object @p f to each element in the range
* @p [first,last). @p f must not modify the order of the sequence.
* If @p f has a return value it is ignored.
*/
template<typename _InputIterator, typename _Function>
_Function
for_each(_InputIterator __first, _InputIterator __last, _Function __f)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
__glibcxx_requires_valid_range(__first, __last);
for (; __first != __last; ++__first)
__f(*__first);
return _GLIBCXX_MOVE(__f);
}
for_each通过值传递复制外面传过来的function object,然后每次将容器中的一个元素作为参数交给function object的函数调用操作,最后将function object返回,又会导致一次拷贝。对于STL的设计,一般都是采用这种方式,所以要求function object不能禁止拷贝操作,而且要尽量小,防止造成较大的性能和内存成本。
for_each通过值传递复制外面传过来的function object,然后每次将容器中的一个元素作为参数交给function object的函数调用操作,最后将function object返回,又会导致一次拷贝。对于STL的设计,一般都是采用这种方式,所以要求function object不能禁止拷贝操作,而且要尽量小,防止造成较大的性能和内存成本。