简体   繁体   English

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

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

From this link从这个链接

Atomically compares the object representation (until C++20)value representation (since C++20) of *this with that of expected, and if those are bitwise-equal, replaces the former with desired (performs read-modify-write operation).以原子方式比较 *this 的 object 表示(C++20 前)值表示(C++20 起)与预期的,如果它们按位相等,则将前者替换为所需的(执行读取-修改-写入操作)。 Otherwise, loads the actual value stored in *this into expected (performs load operation).否则,将存储在 *this 中的实际值加载到预期中(执行加载操作)。

Hence using C++20 , the while loop in the following code must be infinite but It's finite.因此使用C++20 ,以下代码中的while循环必须是无限的,但它是有限的。 Am I wrong or what's happening我错了还是发生了什么

#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";
}

Demo演示

This change (to use value representation instead of object representation) was done as part of P0528R3 (the motivation and story can be found in P0528R0 ).此更改(使用值表示而不是 object 表示)是作为P0528R3的一部分完成的(动机和故事可以在P0528R0中找到)。 As you can see under cppreference's compiler support , neither gcc nor clang implement this feature yet.正如您在cppreference 的编译器支持下看到的那样,gcc 和 clang 都没有实现此功能。 MSVC does on 19.28, but that's not available on compiler explorer, so I cannot check that to verify at the moment. MSVC 在 19.28 上运行,但在编译器资源管理器中不可用,因此我目前无法检查以进行验证。

So at the moment, you're effectively verifying the old behavior.因此,目前,您正在有效地验证旧行为。

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

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