一些C++對象沒有拷貝構造函數,但有移動構造函數。 例如,boost :: promise。 如何使用它們的移動構造函數來綁定這些對象?如何使用boost :: bind與不可複製的參數,例如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;
}
使用指針不太奇怪,這取決於你給什麼對象綁定到。例如,如果您使用的是信號,則可以保存Connection對象,並在對象的dtor中調用disconnect。如果你不使用信號,你可以開發類似的東西,或者將指針包裝在shared_ptr中。 – Kyle 2010-05-14 17:13:35
boost :: promise實際上是一個shared_ptr和一個bool。 這似乎很奇怪,它應該在堆上分配,並跟蹤一個shared_ptr。 – user222202 2010-05-14 17:36:23