我可以将每个移动引用的数组传递给std :: thread吗?

时间:2014-12-09 04:32:29

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

我想做这样的事情:

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«时,我不想要数组的副本。

1 个答案:

答案 0 :(得分:1)

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

还有一句话:你不应该依赖于移动使向量为空的事实。如果您在调用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