首页 文章

为线程构造函数传递一个引用来将它绑定到函数失败?

提问于
浏览
1

我有一个 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 ::载体); _Args = {std :: vector&}]'source_file.cpp:12:21:从这里需要/ usr / include / c / 5 / functional:1505:61:错误:'class std中没有名为'type'的类型: :result_of))(std :: vector&)>'typedef typename result_of <_Callable(_Args ...)> :: type result_type; ^ / usr / include / c / 5 / functional:1526:9:错误:'class std :: result_of)中没有名为'type'的类型)(std :: vector&)>'_M_invoke(_Index_tuple <_Indices ...> )

那么1)这个问题的标准是什么; 2)有没有办法解决它(不是passing a pointer而不是1个额外lambda expression as wrapper)?

1 回答

  • 2

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

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

    Why ?

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

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

相关问题