【问题标题】:Pass a refrence for thread constructor to bind it to function fails?传递线程构造函数的引用以将其绑定到函数失败?
【发布时间】:2017-11-05 14:45:09
【问题描述】:

我有一个void fun(vector<int> & v),我想在实例化线程thread t(fun, v); 时将一个向量传递给它。在C++14 clang 4 编译失败,在MSVC it runs passing a copy 中起作用。

#include <thread>
#include <vector>
#include <iostream>
using namespace std;

void fun(vector<int> & v) {
    v.push_back(13);
}

int main(){
    vector<int> v;
    thread t(fun, v);
    t.join();
    cout << v.size();
}

gcc 5.4.0 错误示例:

在 /usr/include/c++/5/thread:39:0 包含的文件中, 来自 source_file.cpp:1: /usr/include/c++/5/functional: 在“struct”的实例化中 std::_Bind_simple))(std::vector&)>': /usr/include/c++/5/thread:137:59:需要来自 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(std::vector&); _Args = {std::vector

&}]' source_file.cpp:12:21: 从这里需要 /usr/include/c++/5/functional:1505:61: error: no type named ‘type’ in '类 std::result_of))(std::vector&)>' typedef typename result_of<_callable>::type result_type; ^ /usr/include/c++/5/functional:1526:9: 错误:没有名为“type”的类型 '类 std::result_of))(std::vector&)>' _M_invoke(_Index_tuple<_indices...>)

所以 1) 什么是 c++ 标准在这个问题上的立场; 2) 有没有办法解决它(不是passing a pointer,也不是+1 额外lambda expression as wrapper)?

【问题讨论】:

  • 我想你可能需要std::ref
  • @Galik:很好的答案!))It works,但是为什么简单的引用传递不起作用?

标签: c++ multithreading binding arguments c++14


【解决方案1】:

正如评论中Galik 所指出的,您只需要std::ref()

thread t(fun, std::ref(v));

为什么?

这是因为您的函数 fun() 需要一个对左值的引用。但是,当您构造 thread() 时,您的参数副本将在新线程中传递。不幸的是,在这种情况下,编译器将无法通过引用临时副本来实例化幕后的模板。

放置std::ref(),将导致使用对原始文件的引用,并使整个事情按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    相关资源
    最近更新 更多