c++ - 正确使用 volatile 与 std::atomic_ref<T>

标签 c++ atomic volatile mmap atomicreference

我无法理解 std::atomic_ref<int> 的正确用法。与 volatile .

天真地存在三种可能性:

std::atomic_ref<volatile int> ref1;
volatile std::atomic_ref<int> ref2;
volatile std::atomic_ref<volatile int> ref3;

我们何时以及何时需要使用每一个?我感兴趣的用例是 MMIO。

最佳答案

std::atomic<T>不同, std::atomic_ref<T>没有volatile -合格的方法。所以,你可能不能用 volatile std::atomic_ref<T> 做太多事情。 (无论 T 本身是否是 volatile 的)。

鉴于quote,这是有道理的

Like language references, constness is shallow for atomic_ref - it is possible to modify the referenced value through a const atomic_ref object.

假设 cv 限定在某种程度上是一致的,浅 volatile 的atomic_ref 不太可能有用,而且绝对不是您所要求的。

所以,你想要

std::atomic_ref<volatile int>

请注意,仅使用 std::atomic_ref<int>可能就足够了,但由于该标准没有对 MMIO 做出任何明确的保证,因此您可能应该查阅编译器文档和/或检查它生成的代码。

取决于std::atomic这样至少是不可移植的。具体来说,this answer及其 linked paper提及 std::atomic 的一些方式可能不充分 - 您可以检查这些是否是您的实际问题。

关于c++ - 正确使用 volatile 与 std::atomic_ref<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64026734/

相关文章:

c++ - STL vector 分配与插入

c++ - 将函数/构造函数参数限制为特定类型的成员

Java:调用 super.clone() 方法, volatile int 值未复制到克隆对象中

ios - 当在另一个线程上执行 block 时,我应该将 'volatile' 与 '__block' 限定符一起使用吗?

c - 在调试信息/反汇编中识别 volatile 声明

C++如何检查N个对象中的一些对象是否相等

c++ - 在这种情况下,带有 memory_order_seq_cst 的原子读操作读取哪个值?

c++ - _InterlockedCompareExchange64的用法

c++ - 多个快速读取器单个慢速写入器 : is using shadow-data with atomic index safe?

c++ - 在C++ 11中是否有任何等于asm (“”::: “memory”)的编译器障碍?