为什么使用boost::function调用函数对象时不需要类实例

Why no class instance is needed when call a function object with boost::function

本文关键字:对象 不需要 实例 函数 调用 boost function 为什么      更新时间:2023-10-16
#include <iostream>
#include <vector>
#include <string>
#include <ostream>
#include <algorithm>
#include <boost/function.hpp>
using namespace std;
class some_class
{
public:
  void do_stuff(int i) const
  {
    cout << "some_class i: " << i << endl;
  }
};
class other_class
{
public:
  void operator()(int i) const
  {
    cout << "other_class i: " << i << endl;
  }
};
int main() {
  //             CASE ONE
  boost::function<void (some_class, int) > f;
  // initilize f with a member function of some_class
  f = &some_class::do_stuff;
  // pass an instance of some_class in order to access class member
  f(some_class(), 5); 
  //             CASE TWO
  boost::function<void (int) > f2;
  // initialize f2 with a function object of other_class
  f2 = other_class();
  // Note: directly call the operator member function without
  // providing an instance of other_class
  f2(10);
}

// output
~/Documents/C++/boost $ ./p327
some_class i: 5
other_class i: 10

问题>当通过boost::function调用函数对象时,为什么不需要为类提供一个实例来调用该类成员函数?

是因为我们已经通过下面一行提供了这些信息吗?

f2 = other_class();

您必须为类提供一个实例,并且您正在提供一个。

boost::function<void (int) > f2;
f2 = other_class();

构造一个other_class对象,并将该对象赋值给f2boost::function然后复制该对象,所以当你尝试调用它时,你不需要第二次实例化它。

为什么我们不需要为类提供一个实例来调用这个类成员函数?

因为你已经给了它一个。在这里:

f2 = other_class();

您创建了一个other_class实例,f2 复制到自身中。f2不存储other_class::operator()函数;它存储类实例本身。所以当你这样做的时候:

f2(10);

f2 实例存储在其中。它相当于:

other_class()(10);