繁体   English   中英

将 compre_exchange 与 c++20 一起使用是否会比较值表示? (为什么这个例子不同意)

[英]Does using compre_exchange with c++20 compare the value representations? (why doesn't this example agree)

从这个链接

以原子方式比较 *this 的 object 表示(C++20 前)值表示(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";
}

演示

此更改(使用值表示而不是 object 表示)是作为P0528R3的一部分完成的(动机和故事可以在P0528R0中找到)。 正如您在cppreference 的编译器支持下看到的那样,gcc 和 clang 都没有实现此功能。 MSVC 在 19.28 上运行,但在编译器资源管理器中不可用,因此我目前无法检查以进行验证。

因此,目前,您正在有效地验证旧行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM