簡體   English   中英

為什么需要額外的括號來編譯“ std :: thread”函子?

[英]Why extra parenthesis is needed to compile “std::thread” functor?

我正在從“古老的” c ++遷移到較新的C ++ 11,並研究std::thread庫。

class MyThread
{
public:
    int i = 0;
    void operator()()
    {
        for (;i < 10000; i++)
            cout << "Exectuing " << endl;
    }
};

main()我有以下幾行:

thread threadObj( MyThread() );

for (int i = 0; i < 1; i++)
    cout << "Main thread " << endl;

threadObj.join();

它不會編譯最后一行:“表達式必須具有類類型”

thread threadObj( (MyThread()) );添加額外的括號thread threadObj( (MyThread()) ); 解決了問題。

為什么呢 類型保持不變: thread

我是否缺少一些新的c ++ 11功能? 還是我只是感到困惑...

您看到的問題被稱為最煩人的解析: https : //en.wikipedia.org/wiki/Most_vexing_parse

因此,從c ++ 11開始,您可以使用新的'{}'進行初始化。

使用新表格,您可以編寫:

thread threadObj{ MyThread{} };

這將創建一個空初始化器列表的MyThread ,並使用在初始化MyThread{}之前創建的對象創建線程對象本身。

使用以下形式正在發生什么: thread threadObj( MyThread() ); 編譯器將其解釋為函數調用,而不是對象的初始化。 因此,使用新的{}形式使編譯器很容易理解。

如果在程序中使用{} ,則應嚴格使用它。 像這樣使用它:

thread threadObj{ MyThread() }; // bad style!

看起來有點神秘,因為您同時使用了舊版本和新版本。 從技術上講,這是可行的,但會使代碼不可讀。 (至少對於我的眼睛:-))

我是否缺少一些新的c ++ 11功能? 或只是感到困惑。

是的,在c ++ 11中,您使用通用初始化程序。 更改代碼行

thread threadObj( MyThread() );

 thread threadObj{ MyThread() };

它將正常工作

暫無
暫無

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

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