首页 文章

C 11线程编译错误传递字符串作为副本的引用

提问于
浏览
0

我正在学习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&)>':/ usr / local / include / c /4.8.5/thread:137:47:需要'std :: thread :: thread(Callable &&, Args && . ..)[with _Callable = void(&)(std :: basic_string&); _Args = {std :: basic_string,std :: allocator>&}]'thread.cpp:17:20:从这里需要/ usr / local / include / c /4.8.5/functional:1697:61:错误:否'class std :: result_of)中命名为'type'的类型)(std :: basic_string&)>'typedef typename result_of <_Callable(_Args ...)> :: type result_type; ^ / usr / local / include / c /4.8.5/functional:1727:9:错误:'class std :: result_of)中没有名为'type'的类型)(std :: basic_string&)>'_M_invoke(_Index_tuple <_Indices ...>)

任何帮助将受到高度赞赏 .

1 回答

  • 2

    保留它将传递给线程函数的对象的副本,并且当它启动新线程时,它将这些参数作为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 函数时,它将被隐式转换为对用于在主线程中构造它的原始对象的引用 .

相关问题