gpt4 book ai didi

C++ 在基类中使用已删除函数 std::unique_ptr

转载 作者:搜寻专家 更新时间:2023-10-31 02:13:08 25 4
gpt4 key购买 nike

我有一个 vector 或游戏对象。我必须为 C++11 编译

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

Game是基类,这样定义

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;

最佳答案

对于 boost::bind(&Game::play, games_[i], 2)games_[i] 被复制到绑定(bind),但是 std::unique_ptr 无法复制。 (只能移动,但我觉得移动到这里不符合要求。)

您可以使用 boost::ref 来避免复制,例如

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

关于C++ 在基类中使用已删除函数 std::unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41808352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com