为什么std :: atomic对象不可复制? [英] Why are std::atomic objects not copyable?

查看:964
本文介绍了为什么std :: atomic对象不可复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎 std :: atomic 类型不是可复制的或可复制的。
为什么?

It seems that std::atomic types are not copy constructible or copy assignable. Why?

有没有技术原因为什么复制原子类型是不可能的?
或者是为了避免某种错误的代码而有意的接口限制?

Is there a technical reason why copying atomic types is not possible? Or is the interface limited on purpose to avoid some sort of bad code?

推荐答案


  1. 技术原因:大多数原子类型不能保证无锁。

  1. Technical reason: Most atomic types are not guaranteed to be lock-free. The representation of the atomic type might need to contain an embedded mutex and mutexes are not copyable.

逻辑原因:复制一个原子类型是什么意思?原子类型的表示形式可能需要包含嵌入的互斥体,互斥体是不可复制的。将整个复制操作预计是原子的?副本和原件是否代表相同原子对象?

Logical reason: What would it mean to copy an atomic type? Would the entire copy operation be expected to be atomic? Would the copy and the original represent the same atomic object?

对于跨越两个独立原子对象的操作,没有明确定义的含义,你可以做的一件事是将从一个原子对象加载的值传输到另一个。但是加载仅仅与前一个对象上的其他操作同步,而存储与目标对象上的操作同步。每个部分都可以带有完全独立的内存排序约束。

There is no well-defined meaning for an operation spanning two separately atomic objects that would make this worthwhile. The one thing you can do is transfer the value loaded from one atomic object into another. But the load directly synchronizes only with other operations on the former object, while the store synchronizes with operations on the destination object. And each part can come with completely independent memory ordering constraints.

拼写出这样的操作作为加载,后跟一个商店,使得显式,而赋值将留下一个想知道它如何与参与对象的存储器访问属性相关。如果你坚持,你可以通过结合 std :: atomic< ..> 的现有转换(需要显式转换或值类型的其他中间体)来实现类似的效果)。

Spelling out such an operation as a load followed by a store makes that explicit, whereas an assignment would leave one wondering how it relates to the memory access properties of the participating objects. If you insist, you can achieve a similar effect by combining the existing conversions of std::atomic<..> (requires an explicit cast or other intermediate of the value type).

这篇关于为什么std :: atomic对象不可复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆