3

In "The C++ Programming Language Fourth Edition" by "Bjarne Stroustrup",5.3.2. Passing Arguments, there is a code segment:

void f(vector<double>& v);    // function do something with v
int main()
{
     vector<double> some_vec {1,2,3,4,5,6,7,8,9};
     thread t1 {f,some_vec};
}

the declaration of f in first line dont have a const parameter. When I try the following similar code :

void f(string& str) { cout << str << endl; }

int main()
{
    string fstr="ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
    thread t1 {f,fstr};
}

I got the following error:

 /usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<void (*(std::basic_string<char>))(std::basic_string<char>&)>’:
/usr/include/c++/4.8/thread|137 col 47| required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(std::basic_string<char>&); _Args = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >&}]’

so what is going on here?

BTW: if I call f directly, then everything is OK

Galik
  • 47,303
  • 4
  • 80
  • 117
shengyushen
  • 289
  • 3
  • 13

1 Answers1

3

Just had a look here:

http://en.cppreference.com/w/cpp/thread/thread/thread

they say you should use std::ref to pass something as reference.

So in your case, try this:

thread t1 {f, std::ref(fstr)};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
PRIME
  • 1,058
  • 7
  • 21
  • 1
    Thank you, that works, but does this mean the code from "The C++ Programming Language Fourth Edition" by "Bjarne Stroustrup" is incorrect? – shengyushen Dec 26 '15 at 07:58
  • @shengyushen Did you try it? Your question implies it works. Does it? – juanchopanza Dec 26 '15 at 08:00
  • 1
    I have just tried, and find the book example also fail with the same message. Funny. – shengyushen Dec 26 '15 at 08:03
  • But what I don't understand is that why the non-const way is forbidden? – shengyushen Dec 26 '15 at 08:07
  • By referring to http://stackoverflow.com/questions/21048906/stdthread-pass-by-reference-calls-copy-constructor/, its seems that the thread only accept value instead of ref? right? does this mean to avoid data race? – shengyushen Dec 26 '15 at 08:13