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

标签 c++ multithreading

我有如下类 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/

相关文章:

c++ - Valgrind 在不应该的时候报告竞争条件

multithreading - 使用 NXT 进行多线程

c# - 在冷 IObservable 上暂停和恢复订阅

c++ - 如何在 C++ 中添加延迟

C++:为什么 cout 打印回车符以及使用 ifstream 从文件读取的字符串?

c++ - for_each 和转换

c++ - 纤维可以在线程之间迁移吗?

c++ - 如何附加到 C++ 预处理器宏?

c++ - 与 boost::condition_variable 的线程同步

c++ - 实现线程间同步屏障的最佳方法是什么