2017-01-23 57 views
2

我有一個向量或遊戲對象。我必須編譯的C++ 11C++使用刪除函數std :: unique_ptr與基類

std::vector< std::unique_ptr<Game> > games_; 

遊戲是基類,像這樣

class Game { 

public: 

     Game(int id, const std::string& name) 
       : id_(id), name_(name){} 

     virtual ~Game(); 

     int play(int w); 
     virtual void validate() = 0; 

     int id_; 
     std::string name_; 

}; 

派生類只是實現validate()方法定義。

現在我的經理類想要發佈一個「玩遊戲」到線程池。做過這樣的:

void Manager::playGames() { 


     boost::asio::io_service ioService; 

     std::unique_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(ioService)); 

     boost::thread_group threadpool; //pool 
     std::cout << "will start for " << playthreads_ << " threads and " << getTotalRequests() << "total requests\n"; 
     for (std::size_t i = 0; i < playthreads_; ++i) 
       threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService)); 

     for (std::size_t i=0; i < w_.size(); i++) { 

       ioService.post(boost::bind(&Game::play, games_[i], 2)); 

     }  

     work.reset(); 
     threadpool.join_all(); 
     ioService.stop(); 

} 

的錯誤是

/home/manager.cpp: In member function ‘void Manager::playGames()’: 
/home//manager.cpp:65:74: error: use of deleted function 
‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) 
[with _Tp = Game; _Dp = std::default_delete<Game>]’ 
ioService.post(boost::bind(&Game::play, games_[i], 2)); 
                     ^
In file included from /opt/5.2/include/c++/5.2.0/memory:81:0, 
       from /home/manager.hpp:5, 
       from /home/manager.cpp:1: /opt/5.2/include/c++/5.2.0/bits/unique_ptr.h:356:7: note: declared 
here 
     unique_ptr(const unique_ptr&) = delete; 
+0

您在某種程度上要求刪除unique_ptr的副本,因爲它們被定義爲僅在移動。 – Borgleader

回答

2

boost::bind(&Game::play, games_[i], 2)games_[i]被複制到綁定,但std::unique_ptr無法複製。 (它只能移動,但我認爲移動它在這裏將不符合要求。)

您可以使用boost::ref以避免複製,例如,

ioService.post(boost::bind(&Game::play, boost::ref(games_[i]), 2)); 
+1

錯誤:沒有匹配函數調用'get_pointer(std :: reference_wrapper >&)' – cateof

+0

編譯boost :: ref – cateof

+2

@cateof對不起,我不能用boost來測試它,我想你'再右吧。順便說一句'std :: bind'與'std :: ref'很好。 – songyuanyao

相關問題