作者:一颗顽石 | 来源:互联网 | 2023-02-10 14:17
我有类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存在问题,线程是非复制类,我已经改为std :: move,因为 - > ee.threa = std :: move(ee.threa ); this-> ee.timer = std :: move(ee.timer); 但它仍然给我错误,这里有什么问题?
1> int3..:
要使这项工作,您应该更改您的代码:
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代替它们.