gpt4 book ai didi

c++ - 使用已删除的函数 'std::thread::thread(const std::thread&)'

转载 作者:太空狗 更新时间:2023-10-29 20:35:30 31 4
gpt4 key购买 nike

我有如下类 eventEngine 和网关:

class eventEngine
{
public:
eventEngine();

std::thread threa;
std::thread timer;
};

class Gateway
{
protected:
eventEngine ee;
std::string gatewayName;
};

网关的构造函数:

Gateway::Gateway(eventEngine ee, std::string gatewayName)
{

this->ee.threa = std::move(ee.threa);
this->ee.timer = std::move(ee.timer);

this->gatewayName = gatewayName;
}

和 main1.cpp:

int main()
{
eventEngine e;
std::string names = "abc";
Gateway g(e,names);

return 0;
}

当我尝试在 main1.cpp 中编译时,出现错误:

main1.cpp:12:21: error: use of deleted function 'eventEngine::eventEngine(const eventEngine&)'
Gateway g(e,names);
^
In file included from Gateway.h:11:0,
from main1.cpp:2:
eventEngine.h:25:7: note: 'eventEngine::eventEngine(const eventEngine&)' is implicitly deleted because the default definition would be ill-formed:
class eventEngine
^
eventEngine.h:25:7: error: use of deleted function 'std::thread::thread(const std::thread&)'
In file included from Gateway.h:8:0,
from main1.cpp:2:
/usr/lib/gcc/x86_64-pc-cygwin/5.3.0/include/c++/thread:126:5: note: declared here
thread(const thread&) = delete;
^
In file included from Gateway.h:11:0,
from main1.cpp:2:
eventEngine.h:25:7: error: use of deleted function 'std::thread::thread(const std::thread&)'
class eventEngine

我搜索过类似的问题,好像std::thread有问题,thread是非复制类,我改成了std::move this->ee.threa = std::move( ee.threa);this->ee.timer = std::move(ee.timer);但它仍然给我错误,这里有什么问题?

最佳答案

要使其正常工作,您应该更改代码:

Gateway::Gateway(eventEngine&& ee, std::string&& gatewayName)
{
this->ee = std::move(ee);
this->gatewayName = std::move(gatewayName);
}

Gateway g(std::move(e), std::move(names));

或者只是

Gateway g(eventEngine{}, "abc");

但是最好的办法是用标准的形式写:

Gateway::Gateway(eventEngine&& ee, std::string&& gatewayName) : ee{std::move(ee)}, gatewayName{std::move(gatewayName)} {}

您的代码不起作用,因为您尝试使用 copy-ctor 初始化函数参数,该参数因删除 std::thread 和分别的 eventEngine 而被删除的抄袭者。您应该使用 move-ctors 而不是它们。

关于c++ - 使用已删除的函数 'std::thread::thread(const std::thread&)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42514004/

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