问题描述
从此link
以原子方式将* this的对象表示形式(直到C ++ 20)与* this的值表示形式(与C ++ 20起)进行比较,如果按位相等,则将其替换为所需的形式(执行读取-修改-写操作)。否则,将* this中存储的实际值加载到期望值(执行加载操作)。
因此,使用C++20
时,以下代码中的while
循环必须是无限的,但它是有限的。我是错了还是发生了什么
#include <atomic>
#include <iostream>
struct S {
char a{};
int b{};
};
bool operator==(const S& lhs,const S& rhs) {
return lhs.a == rhs.a && lhs.b == rhs.b;
}
int main() {
S expected{ 'a',2 };
std::atomic<S> atomicS{ S{'a',2} };
reinterpret_cast<unsigned char*>(&(atomicS))[1] = 'e';
reinterpret_cast<unsigned char*>(&(expected))[1] = 'f';
while (atomicS.compare_exchange_strong(expected,S{ 'a',2 }));
std::cout << "\nfinished";
}
解决方法
此更改(使用值表示代替对象表示)是在P0528R3中进行的(动机和故事可以在P0528R0中找到)。如您在cppreference's compiler support下所见,gcc和clang都尚未实现此功能。 MSVC在19.28上运行,但是在编译器资源管理器中不可用,因此我目前无法进行验证。
因此,目前,您正在有效地验证旧行为。