将非const引用传递给线程

时间:2015-12-26 07:47:24

标签: c++ multithreading

In" C ++编程语言第四版" by" Bjarne Stroustrup",5.3.2。传递参数,有一个代码段:

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};
}

第一行中f的声明没有const参数。当我尝试以下类似的代码时:

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

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

我收到以下错误:

 /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> >&}]’

那么这里发生了什么?

顺便说一句:如果我直接打电话给f,那一切都没问题

1 个答案:

答案 0 :(得分:0)

看看这里:

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

他们说你应该使用std::ref传递一些东西作为参考。

所以在你的情况下,试试这个:

thread t1 {f, std::ref(fstr)};
相关问题