C ++使用删除函数std :: unique_ptr和Base类

时间:2017-01-23 14:12:50

标签: c++ c++11 boost unique-ptr

我有一个矢量或游戏对象。我必须为c ++ 11编译

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()方法。

现在我的经理班想要发布一个&#34;玩游戏&#34;到一个线程池。做完这样:

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;

1 个答案:

答案 0 :(得分: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));