我有类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); 但它仍然给我错误,这里有什么问题?
答案 0 :(得分:5)
要使这项工作,您应该更改您的代码:
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代替它们。