我无法理解 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/