compare_exchange_weak() 编译错误

compare_exchange_weak() compile error?

本文关键字:编译 错误 weak exchange compare      更新时间:2023-10-16

我的代码如下所示:

void C::addB(std::atomic<B>& b)
{
    B* b2 = b.load();
    B newValue = B();
    bool result = b.compare_exchange_weak(b2, newValue, std::memory_order_relaxed, std::memory_order_release);
}

编译器不断抱怨签名与三成员重载形式的compare_exchaneg_weak不匹配:

note: candidate expects 3 arguments, 4 provided

您的代码给我的错误消息比您发布的片段多得多。最相关的是

error: cannot convert ‘B’ to ‘B*’ in initialisation
note:   no known conversion for argument 1 from ‘B*’ to ‘B&’

指示在需要对象时声明指针:

B b2 = b.load();

http://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange

从上面的 URL 引用原型并相应地传递参数。