现在的位置: 首页 > 综合 > 正文

function object研究之一

2013年10月14日 ⁄ 综合 ⁄ 共 1414字 ⁄ 字号 评论关闭

概念

Function object首先是一个类,它实现了函数调用操作符T operator()(T), T可以是void类型。

最简单的示例:for_each

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

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 a1;
    A a2 = for_each(v.begin(), v.end(), a1);
    cout <<a1.X() << endl;
    cout <<a2.X() << endl;
    return 0;
}

输出结果是:

1
2
0
2

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

_Function __f 这个参数表明for_each会对function object做一次复制。

然后在遍历的时候,每次都调用function object的operator()(int)函数。因为*__first就是指向vector里面的当前元素,类型是int.
return _GLBCXX_MOVE(__f) 表明返回时又会对function object做一次复制。
STL的设计,都是采用这种方式,所以要求function object不能禁止拷贝操作,而且要尽量小,防止造成较大的性能和内存成本。

抱歉!评论已关闭.