簡體   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