C++ Thread taking reference argument failed compile

ⅰ亾dé卋堺 提交于 2019-11-29 02:15:49

I know if I pass a value, the thread will only work on the copy and has no effect after the thread returns.

No, that's not correct. The code should not silently make a copy and work on the copy, the standard says it must not even compile.

The standard requires that the arguments to the called function are copied (into storage managed by the C++ runtime) and then the copies are forwarded as rvalues. So in your example f1 gets passed an rvalue of type double and the parameter of type double& cannot bind to that rvalue.

The reason the standard requires that is so there is no silent copying and loss of data: if the function requires a modifiable reference then it won't compile unless you pass a reference explicitly using a reference_wrapper.

The compiler error you get involves result_of because that's how I made GCC's std::thread check if the function can be called with the supplied arguments. I use result_of<decltype(&f1)(double)> to check if the function pointer &f1 (which is of type void(*)(double&)) can be called with an rvalue of type double. It can't be called with an argument of that type, so the nested type result_of<decltype(&f1)(double)>::type is not defined, so the compiler says:

error: no type named 'type' in 'class std::result_of<void (*(double))(double&)>'

The error is a bit confusing because the C++ declarator rules mean that decltype(&f1)(double) gets displayed as void(*(double))(double&).

That is not my concern. I want to know why it is giving error now, but it was not giving error to other posts on SO

Those posts were using an old pre-C++11 or non-conforming compiler which didn't meet the requirements of the C++11 standard and incorrectly compiled the code.

Jonathan's answer is definitive. Time spent studying it would be time well spent.

In the meantime, modifying the code thus will do what you want - namely send a reference into the thread function:

thread t1(f1, std::ref(ret));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!