2011-06-18 172 views
2

是否有可能將std :: unique_ptr作爲參數傳遞給boost :: thread構造函數?如果不是,什麼是最好的解決方法?boost :: thread和std :: unique_ptr

一個小例子:

// errors: g++ uniqueptr_thread.cpp -std=c++0x 

#include <iostream> 
#include <memory> 
#include <boost/thread.hpp> 

class TestThread{ 
public: 
    void operator()(std::unique_ptr<int> val){ 
    std::cout << "parameter: " << val << std::endl; 
    } 

}; 

int main(int argc, char* argv[]){ 

    std::unique_ptr<int> ptr(new int(5)); 

    boost::thread th(new TestThread(), std::move(ptr)); 

} 

回答

2

這編譯和運行對我來說:

#include <iostream> 
#include <memory> 
#include <thread> 

class TestThread{ 
public: 
    void operator()(std::unique_ptr<int> val){ 
    std::cout << "parameter: " << *val << std::endl; 
    } 
}; 

int main() 
{ 

    std::unique_ptr<int> ptr(new int(5)); 

    std::thread th(TestThread(), std::move(ptr)); 
    th.join(); 

} 

但它必須是C++ 0x中模式。我不知道推動移動模擬是否足以做到這一點。

+0

與哪個編譯器? g ++ 4.4.5給了我比boost版本更長的錯誤列表,使用相同的選項(-std = C++ 0x) – Dutow

+0

@Dwowo:根據C++ 0x,它應該可以工作。如果沒有,那麼你的GCC或libC++版本可能有問題。也許嘗試更近一個? –

+0

我在Mac OS X上使用了clang + libC++(http://llvm.org/),非常接近它們兩者的開發小技巧。 –

2

一個std ::的unique_ptr是,顧名思義,獨特只能有一個!現在

,如果你的線程函數有一個std ::的unique_ptr & &,而你使用std ::搬家搬參數在線程功能,然後可以傳遞的std ::的unique_ptr。但是,你的副本將是空的,因爲你將它移動到另一個線程。

如果std :: move不起作用,那麼你的編譯器或標準庫可能會有錯誤。我想象在這樣的線程間轉移所有權並不是一個普遍的現象。而C++ 11還是相當新的。

+1

+1。我懷疑移動到另一個線程是他想要的。這看起來像將任意對象傳遞給線程的乾淨方式。 – Nemo

+0

對不起,我忘了std ::從示例代碼中移出,它在原來的位置,但它仍然不會編譯 – Dutow

0

你確定你的問題是與unique_ptr?爲什麼你的例子使用new來創建你的函子?該行只能爲:

boost::thread th(TestThread(), std::move(ptr));