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

查看:32
本文介绍了为什么 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?

对于跨越两个单独的原子对象的操作,没有明确定义的意义,这将使这变得值得.您可以做的一件事是将从一个原子对象加载的值转移到另一个原子对象中.但是load直接只和前一个对象上的其他操作同步,而store是和目的对象上的操作同步.并且每个部分都可以带有完全独立的内存排序约束.

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天全站免登陆