【问题标题】:Can I pass an array per move reference to std::thread?我可以将每个移动引用的数组传递给 std::thread 吗?
【发布时间】:2014-12-09 04:32:29
【问题描述】:

我想做这样的事情:

void
Bah::f (std::vector <int> && array)
{
   std::thread (&Bah::foo, this, std::move (array)) .detach ();
}

void
Bah::foo (const std::vector <int> & array)
{
  do something with array
}

问题是:我可以将每个移动引用传递一个数组(变量)到 std::thread,然后在线程函数中作为 const 引用进行访问吗?调用线程函数之前数组移动了吗?

我想要实现的是,我希望在调用 »f« 后数组为空。当 »foo« 被调用时,我不想要数组的副本。

【问题讨论】:

  • 是的,我认为是这样,因为线程的参数存储就像std::decay 应用于每个参数类型一样。此时应该移动矢量内容。但一定要测试一下。 ;-)

标签: c++ multithreading c++11 stl reference


【解决方案1】:

是的,您可以通过这种方式在向量中移动。请参阅下面的小示例,说明移动(实际上将发生 4 次移动以将参数传递给线程)。

还有一点:你不应该依赖 move 使向量为空的事实。如果在调用f 后需要向量为空,则应显式调用clear。在实践中,向量可能是空的,但未指定,标准允许它处于任何“有效”状态。

#include <thread>
#include <iostream>

using namespace std;

class A
{
public:
    A(){};
    A(const A&) { cout << "copy A" << endl; }
    A(A&&) { cout << "move A" << endl; }
};

class B
{
public:
    void bar() 
    { 
        A a;
        thread(&B::foo, this, move(a)).detach(); 
    }
    void foo(const A&) { return; }
};

int main()
{
    B b;
    b.bar();
}

// Output:
// move A
// move A
// move A
// move A

【讨论】:

    猜你喜欢
    • 2013-11-17
    • 2020-12-15
    • 2011-07-17
    • 2016-03-13
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    相关资源
    最近更新 更多