您的位置:首页 > 其它

boost::function 和 boost::bind 的工作原理

2011-03-24 15:21 288 查看
boost::bind(&klass::member, instance, 0, _1) 返回一个函数对象,类似于:

struct unspecified_type {
... some members ...
return_type operator()(int i) const { return instance->*&klass::member(0, i);
}

返回值 return_type 和参数 int 是通过 klass::member 的函数签名以及 bind 绑定式的参数列表推断出来的。

boost::function 并不进行类型检查,可以使用任意函数签名式(模版参数)和任意可调用物来创建一个函数对象,并按照指定的函数签名式执行对象调用,如果该调用不符合函数签名式则会产生编译错误。

boost::function 实际是一个函数对象,类似于:

template <class Sig>
class function {
function_impl<Sig>* f;
public:
return_type operator()(argument_type arg0) const { return (*f)(arg0); }
};

返回值类型 return_type 和参数类型 argument_type 是从模版参数 Sig 中提取出来的,成员 f 是在 heap 上动态分配的,使得任意大小的函数对象都可以绑定到 boost::function 上。

function_impl 只是个 abstract class

template <class Sig>
class function_impl {
public:
virtual return_type operator()(argument_type arg0) const=0;
};

负责具体工作的是派生自 boost::function_impl 的实现类,每种赋值给 boost::function 的函数类型都有一个具体的对象类型:

template <class Sig, class Object>
class function_impl_concrete : public function_impl<Sig> {
Object o
public:
virtual return_type operator()(argument_type arg0) const=0 { return o(arg0); }
};

这意味着在实际运用中将可调用物赋值给 boost::function 将发生下面的事情:
1. 实例化一个函数对象类型 function_impl_concrete<void(int), unsepcified_type> (当然,这是发生在编译期);
2. 在 heap 上动态创建一个该类型的对象;
3. 将该对象赋值给 boost::function 的成员f;

当调用该函数对象时,将执行实现类上的虚函数,进而执行原始的可调用物。

参考资料

1. how boost::function and boost::bind work

2. 侯捷:Boost.Function内核剖析

3. Code Walk-through: How exactly does bind work (with placeholders) ?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: