小编ale*_*833的帖子

为什么 std::thread() 按值传递参数(以及为什么 Stroustrup 博士给出的原因是不正确的)?

引自 The C++ Programming Language(作者:Bjarne Stroustrup),第1213页

\n
\n

线程构造函数是variadic templates(\xc2\xa728.6)。这意味着要将引用传递给线程构造函数,我们必须使用引用包装器 (\xc2\xa733.5.1)。

\n

例如:

\n
void my_task(vector<double>& arg);\nvoid test(vector<double>& v)\n{\n    thread my_thread1 {my_task,v};           //oops: pass a copy of v\n    thread my_thread2 {my_task,ref(v)};      // OK: pass v by reference\n    thread my_thread3 {[&v]{ my_task(v); }}; // OK: dodge the ref() problem\n    // ...\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

问题是variadic templates通过引用目标函数传递参数没有问题。

\n

例如:

\n
void g(int& t)\n{\n}\n\ntemplate <class... T>\nvoid f(T&&... t)\n{\n    g(std::forward<T>(t)...);\n}\n\nint main()\n{\n    int i;\n    f(i);\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

按值传递的唯一原因是标准要求在参数上std::thread …

c++ reference stdthread

7
推荐指数
2
解决办法
151
查看次数

为什么 std::thread 接受通用 lambda 但不接受模板化函数(没有显式实例化)?

为什么在没有任何专门化的情况下将通用 lambda 传递给 std::thread() 是合法的,而另一方面,这对于函数模板来说是非法的。

下面演示了我的查询。

#include <thread>

template <class T>
void f(T t)
{
}

int main()
{
    std::thread t([](auto i){}, 1);  // Works
    std::thread t(f, 1);          // Doesn't work
    std::thread t(f<int>, 1);     // Works

    t.join();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ lambda templates stdthread

4
推荐指数
1
解决办法
81
查看次数

标签 统计

c++ ×2

stdthread ×2

lambda ×1

reference ×1

templates ×1