一些C对象没有复制构造函数,但是具有移动构造函数.
例如,boost :: promise.
如何使用移动构造函数绑定这些对象?
例如,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;
}
解决方法
我看到你使用std :: move.为什么不使用std :: bind,应该知道移动语义?
template<class F,class... BoundArgs> unspecified bind(F&&,BoundArgs&&...); template<class R,class F,BoundArgs&&...);
关于宣布fullfil_1的移动版本
void fullfil_1(boost::promise<int>&é prom,int x)
{
prom.set_value(x);
}
Boost.Bind不支持移动语义(至少我不知道).我希望当前评论的Boost.Move将被接受,Boost.Bind,Boost.Lambda和Boost.Phoenix将添加移动语义界面.
您可以尝试撰写参考并移动如下
boost::function<void()> f_set_one = boost::bind(&fullfil_1,boost::ref(std::move(pi)),1);

