這個問題在這里已經有了答案: 最令人頭疼的決議 C 11 2 個答案 Most Vexing Parse 的目的是什么? (6 個回答) 最令人煩惱的是決議一個正式定義的概念 2 個答案 2 小時前關閉。
我想將 std::thread 臨時物件直接傳遞給我的 ThreadGuard 類,但不知何故不會產生任何輸出,但是如果我首先創建本地 std::thread 變數并將其傳遞給建構式,那么它作業正常。所以我的問題是我們不能將臨時執行緒傳遞給采用右值參考引數的函式嗎?
#include <iostream>
#include <thread>
using namespace std;
class ThreadGuard
{
private:
std::thread& m_t;
public:
ThreadGuard(std::thread& t):m_t(t)
{
std::cout<<"By lvalue ref constructor "<<std::endl;
}
ThreadGuard(std::thread&& t):m_t(t)
{
std::cout<<"By rvalue ref constructor "<<std::endl;
}
~ThreadGuard()
{
if(m_t.joinable())
{
m_t.join();
}
}
};
void foo()
{
std::cout<<"Inside foo..."<<std::endl;
}
int main()
{
//This is working
//std::thread th(foo);
//ThreadGuard t1(th);
//This is not giving any output
ThreadGuard t(std::thread(foo));
return 0;
}
uj5u.com熱心網友回復:
您剛剛遇到的是 C 中最令人頭疼的決議語法。
編譯器認為您已經宣告了一個t回傳 aThreadGuard并接受footype 引數的函式std::thread:
ThreadGuard t(std::thread foo);
一種可能的解決方案是使用花括號進行初始化,如下所示:
ThreadGuard t(std::thread{foo});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/517026.html
標籤:C 多线程
