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

Can I pass an array per move reference to std::thread?

本文关键字:std thread 数组 引用 移动 我可以      更新时间:2023-10-16

我想做这样的事情:

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

是的,您可以通过这种方式在矢量中移动。请参阅下面的一个小示例,说明移动(实际上会发生 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