为什么使用boost::function调用函数对象时不需要类实例
Why no class instance is needed when call a function object with boost::function
#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
对象,并将该对象赋值给f2
。boost::function
然后复制该对象,所以当你尝试调用它时,你不需要第二次实例化它。
为什么我们不需要为类提供一个实例来调用这个类成员函数?
因为你已经给了它一个。在这里:
f2 = other_class();
您创建了一个other_class
实例,f2
将复制到自身中。f2
不存储other_class::operator()
函数;它存储类实例本身。所以当你这样做的时候:
f2(10);
f2
将实例存储在其中。它相当于:
other_class()(10);
相关文章:
- 为什么模板类中的对象不能返回值
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 当我不需要数据库中的所有值时,如何部分初始化 c++ 对象?
- 为什么复制构造函数不需要检查输入对象是否指向自身?
- 在同一内存地址上不需要的对象的创建
- 方法用于最快的分配,并且不需要将动态大小的数组对象作为局部变量
- 为什么在调用 glDrawArray 之前不需要绑定顶点缓冲区对象?
- win32 之上的面向对象的库,不需要控制主事件循环
- glDrawArrays() 会自动绘制另一个不需要的对象
- OpenGL尝试翻译对象,但相机也会翻译,我不需要
- 为什么这个函数对象不需要指定的
- 为什么使用boost::function调用函数对象时不需要类实例
- 在c++ 11中,是否有一种方法可以在调用以任何可调用对象(包括绑定方法)作为参数的函数时不需要模板参数
- 向列表中添加临时对象,不需要动态内存分配
- 对象切片,不需要额外的实例方法和变量
- 创建多个对象而不需要多个声明
- 为什么在堆上初始化对象时需要指针,而不需要在堆栈上初始化
- c++中有没有一种方法可以初始化一些类对象的数组,而不需要先定义大小
- c++:包含对象的确切类型,不需要强制类型转换
- C++,不需要修改队列中的(随机)对象,对象指针