COPY分配被禁用于C 11中的线程
Copy assignment is disabled for thread in C++11
void exec_produce(int duration) {
//阻止线程运行到duration秒
this_thread::sleep_for(chrono::seconds(duration));
//this_thread::get_id()获取当前线程id
cout << "exec_produce thread " << this_thread::get_id()
<< " has sleeped " << duration << " seconds" << endl;
}
int main(int argc, const char *argv[])
{
thread threads[5];
cout << "create 5 threads ..." << endl;
for (int i = 0; i < 5; i++) {
threads[i] = thread(exec_produce, i + 1);
}
cout << "finished creating 5 threads, and waiting for joining" << endl;
//下面代码会报错,原因就是copy操作不可用,相当于是delete操作,所以报错
/*for(auto it : threads) {
it.join();
}*/
for (auto& it: threads) {
it.join();
}
cout << "Finished!!!" << endl;
system("pause");
return 0;
}
我想知道为什么代码threads[i] = thread(exec_produce, i + 1);
正确?它不使用复制功能吗?我认为该规则如下:
1(移动分配操作:线程&amp;操作员=(thread&amp;&amp; rhs(noexcept,如果当前对象未加入,则需要将正确的值参考(RHS(传递给移动分配操作;如果当前对象可以连接,则终止((错误。
2(禁用复制分配:线程&amp;operator =(const thread&amp;(=删除,线程对象无法复制。
不,这是移动函数。
使用=
时,如果可能的话,将执行移动(也就是说,如果通过RVALUE,并且是否存在移动分配运算符(。只有在不可能的情况下,才会尝试副本。最便宜的操作是默认的。
您可以在引用的规则中清楚地看到两个操作可以由=
操作员表示。
no,代码是正确的。
行threads[i] = thread(exec_produce, i + 1);
将调用移动分配。 thread(exec_produce, i + 1)
是一个R值,因为它在内存中没有定义的位置(刚刚创建并且尚未存储在变量中(。因此,将调用移动分配。
相关文章:
- 用于矢量处理的多个线程
- 如何在Qt中合并/追加/添加两个用于线程的模型?
- 循环中的线程 Runnin 用于对 c++ 中的数字求和
- 用于线程间通信的 Windows 套接字
- 用于在C++中计算用户数据的线程
- QTcpSocket 或 QSslSocket 是否会自动创建用于读取/写入的线程?
- STD ::原子与静态变量用于线程同步
- COPY分配被禁用于C 11中的线程
- 多个boost io_service在单独的线程上用于多个网卡
- 来自 boost 的 udp 服务器不适用于多线程,但仅在主线程上工作
- 同步线程安全的API,用于暴露缓存数据
- C 两个线程一个用于输入,一个用于输出
- 标准::atomic_应该如何...<std::shared_ptr>用于线程安全类的复制和移动操作?
- c++线程池:std::函数的替代品,用于将函数/lambdas传递给线程
- 使用mt19937_64生成随机数,用于多线程蒙特卡罗模拟
- 用于录像机的多线程
- 适用于 C++11 的线程,使用 new 创建
- 用于在磁盘上进行内容检索(GET)和数据写入的多个线程
- 适用于 C++11 的 Clang++ 3.3 中的线程支持
- 是否可以将Qt GUI拆分为多个线程用于GUI,仿真和OpenGL