【发布时间】:2015-10-03 17:24:52
【问题描述】:
我使用以下最小示例来重现当我尝试创建一个调用非静态成员函数来完成其工作的线程时遇到的编译器错误:
#include <thread>
#include <iostream>
class Worker
{
public:
Worker() : m_worker(&Worker::doWork, std::ref(*this), 1)
{}
std::thread m_worker;
void doWork(int a) { std::cout << a << std::endl; }
};
int main(int argc, char* argv[]) {
Worker k;
}
使用 gcc4.8-gcc5.1 编译失败,原因如下:
In file included from /usr/include/c++/4.8/thread:39:0,
from /tmp/gcc-explorer-compiler115614-69-rgangs/example.cpp:1:
/usr/include/c++/4.8/functional: In instantiation of 'struct std::_Bind_simple<std::_Mem_fn<void (Worker::*)(int)>(std::reference_wrapper<Worker>, int)>':
/usr/include/c++/4.8/thread:137:47: required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Worker::*)(int); _Args = {std::reference_wrapper<Worker>, int}]'
7 : required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named 'type' in 'class std::result_of<std::_Mem_fn<void (Worker::*)(int)>(std::reference_wrapper<Worker>, int)>'
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/4.8/functional:1727:9: error: no type named 'type' in 'class std::result_of<std::_Mem_fn<void (Worker::*)(int)>(std::reference_wrapper<Worker>, int)>'
_M_invoke(_Index_tuple<_Indices...>)
^
Compilation failed
另一方面,Clang 似乎可以很好地编译这段代码。谁是正确的,这是 gcc 中的一个错误(有开放票吗?)?
编辑: 当使用m_worker(&Worker::doWork, this, 1) 初始化线程时,gcc 编译它就好了。那么,在这种情况下使用std::ref(*this) 是否合法?我猜任何std::ref(),更笼统。
【问题讨论】:
-
@LightnessRacesinOrbit 确实有所作为,谢谢,现在回答为什么这会有所作为以及是否合法会很酷
-
见cplusplus.github.io/LWG/lwg-active.html#2219 这将在某一天修复。
标签: c++ gcc c++14 standards-compliance