C 11线程汇编错误传递字符串作为复制的引用

C++11 threads compilation error in passing string as reference of copy

本文关键字:复制 引用 字符串 线程 汇编 错误      更新时间:2023-10-16

我正在学习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::threadstd::reference_wrapper<std::string>对象传递到您的hello函数时,它将被隐式转换为用于在主线程中构造它的原始对象的引用。