Home C++ Thread taking reference argument failed compile
Reply: 0

C++ Thread taking reference argument failed compile

user2389 Published in May 21, 2018, 9:17 am
using namespace std;

void f1(double& ret) {

int main() {
   double ret=0.;
   thread t1(f1, ret);
   cout << "ret=" << ret << endl;

The above code fails compilation with the following error message:

g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
In file included from /usr/local/include/c++/5.3.0/thread:39:0,
                 from main.cpp:2:
/usr/local/include/c++/5.3.0/functional: In instantiation of 'struct std::_Bind_simple<void (*(double))(double&)>':
/usr/local/include/c++/5.3.0/thread:137:59:   required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(double&); _Args = {double&}]'
main.cpp:11:21:   required from here
/usr/local/include/c++/5.3.0/functional:1505:61: error: no type named 'type' in 'class std::result_of<void (*(double))(double&)>'
       typedef typename result_of<_Callable(_Args...)>::type result_type;
/usr/local/include/c++/5.3.0/functional:1526:9: error: no type named 'type' in 'class std::result_of<void (*(double))(double&)>'

I understand that I can use std::ref() to pass the argument. But if I pass by value, why is it an error since thread should just copy the argument by value and pass some object stored inside thread to bind with the reference argument of function f1.

I feel that if I can understand what this result_of is doing and why it is giving error, I can better understand the reason. So could anyone walk me through the error msg? Especially the meanings of std::_Bind_simple<void (*(double))(double&)> and std::result_of<void (*(double))(double&)>.

EDIT: I know if I pass a value, the thread will only work on the copy and has no effect after the thread returns. 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 like the following:Difference between pointer and reference as thread parameter

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.513794 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO