C 11线程汇编错误传递字符串作为复制的引用
C++11 threads compilation error in passing string as reference of copy
我正在学习C 11线程,并且在编译以下程序时面临问题。
我无法弄清楚这个问题,因为一切似乎都正确。
#include <iostream>
#include <thread>
#include <unistd.h>
using namespace std;
void hello(string& s)
{
s = "HELLO";
cout << "Hello thread created" << endl;
}
int main()
{
cout << "main thread created" << endl;
string s = "HEY";
thread t(hello, s);
t.join();
cout << s << endl;
return 0;
}
我的G 版本是4.8.5,我正在Centos-7.2上编译它使用命令:
g++ thread.cpp -std=c++11 -pthread
我遇到的错误是:
在/usr/local/include/c /4.8.5/thread:39:0中包含的文件中 来自thread.cpp:2:/usr/local/include/c /4.8.5/functional:在'struct的实例化中 std :: _ bind_simple(((std :: basic_string&amp;(>’: /USR/local/include/c /4.8.5/thread:137:47:需要 ‘std :: thread :: thread(_callable&amp;&amp;,_args&amp;&amp; ...([with _callable = void = void (&amp;((std :: basic_string&amp;(;_args = {std :: basic_string,std ::分配器>&amp;}]’thread.cpp:17:20:
从这里/usr/local/include/c /4.8.5/functional:1697:61需要 错误:在"类std :: result_of(中没有名为"类型"的类型((std :: basic_string&amp;(>’ typedef typeName result_of&lt; _ callable(_args ...(> :: type esluct_type; ^/USR/local/include/c /4.8.5/functional:1727:9:错误:无类型 "类型"在" std :: result_of(中((std :: basic_string&amp;(>’ _m_invoke(_index_tuple&lt; _indices ...>(
任何帮助都将不胜感激。
std::thread
保留将传递给线程函数的对象的副本,当它启动新线程时,它将这些参数传递给线程作为rvalues。非const lvalue-References参考无法绑定到rvalues,因此您的hello
函数的参数不能绑定到对象std::thread
试图传递给对象。
如果要避免这种复制行为,请使用std::reference_wrapper
:
int main()
{
cout << "main thread created" << endl;
string s = "HEY";
thread t(hello, std::ref(s));
t.join();
cout << s << endl;
return 0;
}
std::reference_wrapper<T>
是一个对象的对象,并且复制时仅复制引用。它还具有隐式转换为T&
,因此,当std::thread
将std::reference_wrapper<std::string>
对象传递到您的hello
函数时,它将被隐式转换为用于在主线程中构造它的原始对象的引用。
- 深层复制具有自引用指针的类
- 对复制 CTOR 和 CTOR 的未定义引用
- 为什么我的运算符 + 重载尽管是通过引用传递的,但仍调用我的复制构造函数?
- 在引用初始化中使用已删除的复制构造函数进行复制初始化
- 关于隐式声明的复制构造函数的引用在逻辑上不清楚
- C++:右值引用构造函数和复制省略
- 通过基类接受方法转发派生 UniquePtr 的右值会移动引用而不是复制
- 如何复制只引用基类的派生类
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- C++为具有引用成员变量的类创建复制构造函数
- std::vector 是否有用于引用的复制构造函数?
- 是复制了新数组还是指向结构中引用的数组的指针?
- 可移动但不可复制的对象:按值传递还是按引用传递?
- 通过引用传递是否涉及复制地址
- 复制引用结构上的赋值
- 在 c++ 中复制对未初始化对象的引用
- C++自动生成的具有常量和非常量引用的复制构造函数
- 如何保存指向抽象基类的指针/引用,但在 c++ 中仍然可以复制
- Icpc错误隐式生成的赋值运算符无法复制引用成员(boost图)
- 函数复制引用字符数组中的数据