2010-05-14 73 views
10

一些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; 
} 
+0

使用指針不太奇怪,這取決於你給什麼對象綁定到。例如,如果您使用的是信號,則可以保存Connection對象,並在對象的dtor中調用disconnect。如果你不使用信號,你可以開發類似的東西,或者將指針包裝在shared_ptr中。 – Kyle 2010-05-14 17:13:35

+0

boost :: promise實際上是一個shared_ptr和一個bool。 這似乎很奇怪,它應該在堆上分配,並跟蹤一個shared_ptr。 – user222202 2010-05-14 17:36:23

回答

4

我不知道如何使用移動構造函數來代替,但另一種方法是使用創建的對象可複製引用的boost ::裁判,然後可以把它們進入的boost ::綁定。

+0

只要提到的對象存在,不會提升:: ref工作嗎? – 2010-05-14 18:10:41

+0

是的,所以你需要擔心你正在使用的物體的壽命。 – swestrup 2010-05-15 17:57:39

5

我看到你使用std :: move。爲什麼不使用std :: bind應該知道移動語義?

template<class F, class... BoundArgs> 
unspecified bind(F&&, BoundArgs&&...); 
template<class R, class F, class... BoundArgs> 
unspecified bind(F&&, BoundArgs&&...); 

WHT有關聲明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將添加移動語義接口。

你可以嘗試作曲ref和移動如下

boost::function<void()> f_set_one = boost::bind(&fullfil_1, boost::ref(std::move(pi)), 1); 
相關問題