2017-02-28 41 views
3

我有類eventEngine和網關象下面這樣:使用刪除功能 '的std ::螺紋::線程(常量的std ::絲線)'

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,如this-> ee.threa = std ::移動(ee.threa); this-> ee.timer = std :: move(ee.timer); 但它仍然給我錯誤,這裏有什麼問題?

+2

「網關」的構造函數通過值獲取「eventEngine」(試圖複製它)。 'eventEngine'包含一個'std :: thread'; 'std :: thread'不能被複制。 –

+1

'eventEngine ee' - 這是一個* by-value *引擎的'main'副本。你不能複製'std :: thread',並且由於'eventEngine'具有'std :: thread'實例成員,所以你不能在'eventEngine'上使用默認的copy-construction或者copy-assignmen。你*可以*提供你自己的覆蓋,但我懷疑這是你想要的目標。通過引用傳遞您的ctor參數。 – WhozCraig

+0

std :: thread'類提供的模型是它的實例代表實際資源*,而不僅僅是一個實際資源的引用*。因此,如你所寫的'eventEngine'類,它也代表*實際資源*。正如它的書面材料,你的頭腦中使用了錯誤的語義 - 你不應該認爲複製一個'eventEngine'實例或者按值傳遞它是有意義的。 – Hurkyl

回答

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)} {} 

您的代碼不工作,因爲你嘗試初始化與拷貝構造函數,這是由於刪除,刪除std::thread的分別eventEngine的複製構建函數函數的參數。你應該使用move-ctors而不是它們。

+1

哦,它的工作原理!你是完全真棒 –

+1

雖然這段代碼是受歡迎的,並且可能會提供一些幫助,但它會[如果它包含一個解釋](/ meta.stackexchange.com/q/114762)* how *和* *解決了這個問題。請記住,你正在爲將來的讀者回答這個問題,而不僅僅是現在問的人!請編輯您的答案以添加解釋,並指出適用的限制和假設。特別是,爲什麼笨拙的'this-> ee = std :: move(ee);'語句而不是簡單的初始化程序:'ee {std :: move(ee)}'? –