向线程传递非常数引用
passing non-const reference to a thread
在"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)};
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 列出生成器(lambda的向量)会导致通过引用捕获的非常奇怪的行为
- 从对象调用成员对象,错误:引用非常量值的初始值必须是左值
- 一个非常弱的引用(无法转换为共享)
- 阻止const类函数在引用成员上调用非常常量类函数