我可以将数组每次移动引用传递给 std::thread 吗?
Can I pass an array per move reference to std::thread?
我想做这样的事情:
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
相关文章:
- 在std::thread中,joinable()然后join()线程安全吗
- 分离一个静态常量 std::thread?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 如何从 std::thread 返回值
- 将 std::thread by 值推送到列表中
- 转发变量参数列表以模拟 std::thread
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- std::thread 增加 DLL 引用计数,从而防止卸载 DLL
- 如何防止 std::thread 在 QT 中冻结 GUI?
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- 为什么参数在构造 std::thread 时移动两次
- std::thread::_Invoker 使用线程编程时出错
- 在线程 A 中创建一个 std::thread 对象,在线程 B 中连接
- 为什么编译器抱怨 std::thread 参数在转换为右值后必须是可调用的?
- ZeroMQ 在使用 std::thread 创建工作线程时崩溃
- 在没有复制构造函数的对象的成员函数中启动 std::thread
- CLang:在 std::thread 中运行函数会导致结构创建BAD_ACCESS
- 调用以CWinThread为基的类运算符()的std::thread失败
- 如何通过std::thread生成多个线程
- std::future::get()或std::future::wait()是std::thread::join()的替