某些 C++ 对象没有复制构造函数,但有移动构造函数。
例如,boost::promise。
如何使用它们的移动构造函数绑定这些对象?
#include <boost/thread.hpp>
void fullfil_1(boost::promise<int>& prom, int x)
{
prom.set_value(x);
}
boost::function<void()> get_functor()
{
// boost::promise is not copyable, but movable
boost::promise<int> pi;
// compilation error
boost::function<void()> f_set_one = boost::bind(&fullfil_1, pi, 1);
// compilation error as well
boost::function<void()> f_set_one = boost::bind(&fullfil_1, std::move(pi), 1);
// PS. I know, it is possible to bind a pointer to the object instead of
// the object itself. But it is weird solution, in this case I will have
// to take cake about lifetime of the object instead of delegating that to
// boost::bind (by moving object into boost::function object)
//
// weird: pi will be destroyed on leaving the scope
boost::function<void()> f_set_one = boost::bind(&fullfil_1, boost::ref(pi), 1);
return f_set_one;
}
我不确定如何使用移动构造函数,但另一种方法是使用 boost::ref 创建对对象的可复制引用,然后您可以将它们传递给 boost::bind。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)