2017-01-23 2 views
2

私はベクトルまたはゲームオブジェクトを持っています。私は11C++の削除された関数std :: unique_ptrの基本クラスの使用

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

ゲームは、派生クラスだけでvalidate()メソッドを実装し、この

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_; 

}; 

のように定義された基本クラスであり、C++用にコンパイルする必要があります。

私のマネージャークラスは、スレッドプールに「ゲームをプレイ」したいと思っています。このように完了:

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(); 

} 

エラーがboost::bind(&Game::play, games_[i], 2)については、games_[i]をバインドするためにコピーされ

/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

ですが、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申し訳ありませんが、もう一度。 BTW 'std :: bind'を' std :: ref'と組み合わせても問題ありません。 – songyuanyao

関連する問題