向线程传递非常数引用

passing non-const reference to a thread

本文关键字:引用 非常 线程      更新时间:2023-10-16

在"Bjarne Stroustrup"的"C++编程语言第四版"中,5.3.2。传递Arguments时,有一个代码段:

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

那这是怎么回事?

BTW:如果我直接调用f,那么一切都正常

刚刚看了一下这里:

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

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

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

thread t1 {f, std::ref(fstr)};