我正在使用带有 c++11 标志的 g++4.7。在这个演示中:
#include <iostream>
#include <thread>
class do_work
{
public:
void operator()()
{
std::cout << "Doing work..." << std::endl;
}
};
void foo()
{
}
int main()
{
// Does not work
std::thread t(do_work);
t.join(); // error: request for member ‘join’ in ‘t’, which is of non-class type ‘std::thread(do_work)’
// Works
std::thread t2(foo);
t2.join();
return 0;
}
我可以在使用函数作为其构造函数参数创建的线程上成功调用 join(),但我无法在使用仿函数作为其构造函数参数创建的线程上调用 join()(请参阅内联错误) .谁能解释一下?
最佳答案
您已将 t
声明为接受 do_work
并返回 std::thread
的函数。
你可能想写
do_work worker;
std::thread t{worker};
或
std::thread t{do_work{}};
或
std::thread t((do_work()));
注意
std::thread t(do_work());
不会工作;这是vexingly parsed就像声明一个函数 t
接受一个不带参数并返回 do_work
的函数,并返回 std::thread
。用括号将 do_work
临时包装起来或使用统一的初始化语法(在任何时候)将修复它。
这是养成尽可能使用统一初始化语法的习惯的一个很好的理由;如果你写了
std::thread t{do_work}; // incorrect
那么编译将在该行而不是 join
处失败。
关于c++11 std::thread 使用函数编译,但不使用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12535179/