最近使用c++11 的标准thread库,发现传参的时候的bug,很隐密。
...
/usr/include/c++/4.8.2/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::unordered_map<int, int>, int, int))(std::unordered_map<int, int>&, int, int)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
...
这个错误确实很神秘,但问题是thread_add
它通过引用获取它的第一个参数,但是你按值传递它。这会导致仿函数类型推断错误。如果你想通过引用传递一些实际的函数std::bind
或者像a 的main函数那样std::thread
,你需要使用一个引用包装器(std::ref
):
所以当你传的参数是引用的时候,GCC不会使用这个奇怪的消息进行编译。你可以通过使用带线程的引用包装器来摆脱它
t[0] = thread(thread_add, std::ref(ht), 0, 9);
t[1] = thread(thread_add, std::ref(ht), 10, 19);
这将成功编译。并且线程使用的每个引用都将引用相同的对象。
这是一种传参时是引用的报错,这时候用std::ref()装饰一下就可以了。
还有一种是类的this指针问题。具体的话参照我找到的问题文章看下:
https://segmentfault.com/q/1010000004413576