为什么需要额外的括号来编译" std :: thread"函子?

时间:2018-03-29 15:15:14

标签: c++ multithreading c++11

我是从#34;古代" 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();

它不会编译最后一行:&#34;表达式必须具有类类型&#34;

thread threadObj( (MyThread()) );添加额外的括号可以解决问题。

为什么?类型保持不变:thread

我错过了一些新的c ++ 11功能吗?或者我只是困惑......

2 个答案:

答案 0 :(得分:4)

您看到的问题被称为最令人烦恼的解析:http://www.cplusplus.com/reference/new/operator%20delete[]/

因此,从c ++ 11开始,您可以使用新的“{}”进行初始化。

使用新表格,您可以写:

thread threadObj{ MyThread{} };

这会创建MyThread,其中包含一个空的初始化列表,而线程对象本身则包含之前使用MyThread{}初始化创建的对象。

使用表单进行了什么:thread threadObj( MyThread() );? 编译器将其解释为函数调用,而不是对象的初始化。因此,使用新的{}表单可以清楚地了解编译器。

如果您在程序中使用{},则应严格使用它。使用它像:

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

看起来有点神秘,因为你在一行中使用旧版本和新版本。这在技术上有效,但使代码不可读。 (至少对我而言:-))

答案 1 :(得分:0)

  
    

我错过了一些新的c ++ 11功能吗?或者只是困惑。

  

是的,在c ++ 11中,您使用通用初始值设定项。改变代码行

thread threadObj( MyThread() );

作为

 thread threadObj{ MyThread() };

它会正常工作