为什么编译函子需要额外的括号"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
。
我是否错过了一些新的C 11功能?还是我只是困惑...
您看到的问题被称为最烦人的解析:https://en.wikipedia.org/wiki/wiki/most_vexing_parse_parse
出于C 11的原因,您可以使用新的'{}'进行初始化。
使用新表格可以写:
thread threadObj{ MyThread{} };
这将使用一个空的初始化器列表和线程对象本身创建MyThread
,并使用MyThread{}
初始化创建的对象。
使用以下表格:thread threadObj( MyThread() );
是怎么回事?编译器将其解释为函数调用,而不是对象的初始化。因此,使用新的{}
表单可以使编译器清楚。
如果您在程序中使用{}
,则应严格使用它。使用它:
thread threadObj{ MyThread() }; // bad style!
看起来有些神秘,因为您在旧版本和新版本中使用。从技术上讲,这有效,但使代码不可读。(至少对于我的眼睛:-)(
我是否错过了一些新的C 11功能?或只是困惑。
是,在C 11中,您使用通用初始化器。更改代码
的行thread threadObj( MyThread() );
AS
thread threadObj{ MyThread() };
它将正常工作
相关文章:
- 在std::thread中,joinable()然后join()线程安全吗
- 分离一个静态常量 std::thread?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 如何从 std::thread 返回值
- 将 std::thread by 值推送到列表中
- 转发变量参数列表以模拟 std::thread
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- std::thread 增加 DLL 引用计数,从而防止卸载 DLL
- 如何防止 std::thread 在 QT 中冻结 GUI?
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- 为什么参数在构造 std::thread 时移动两次
- std::thread::_Invoker 使用线程编程时出错
- 在线程 A 中创建一个 std::thread 对象,在线程 B 中连接
- 为什么编译器抱怨 std::thread 参数在转换为右值后必须是可调用的?
- ZeroMQ 在使用 std::thread 创建工作线程时崩溃
- 在没有复制构造函数的对象的成员函数中启动 std::thread
- CLang:在 std::thread 中运行函数会导致结构创建BAD_ACCESS
- 调用以CWinThread为基的类运算符()的std::thread失败
- 如何通过std::thread生成多个线程
- std::future::get()或std::future::wait()是std::thread::join()的替