簡體   English   中英

使用已刪除的函數'std :: thread :: thread(const std :: thread&)'

[英]use of deleted function 'std::thread::thread(const std::thread&)'

我有類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); 但它仍然給我錯誤,這里有什么問題?

要使這項工作,您應該更改您的代碼:

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::threadeventEngine的copy- eventEngine而被刪除。 你應該用move-ctors代替它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM