Documentation Home >> Headers >> <atomic> Header >> std::atomic >> std::atomic::compare_exchange_weak member function

Atomically compare the value to an expected value, and store a new value if the values are equal. If the values were not equal, update the expected value with the value read. Additionally, this may fail spuriously (and return false) even if the values were equal, if the value could not be updated atomically.

bool compare_exchange_weak(
    BaseType& expected,BaseType new_value,
    memory_order order = std::memory_order_seq_cst)
    volatile;
bool compare_exchange_weak(
    BaseType& expected,BaseType new_value,
    memory_order success_order,
    memory_order failure_order) volatile;

Preconditions:

failure_order shall not be std::memory_order_release or std::memory_order_acq_rel.

Effects:

Atomically compares expected to the value stored in *this and stores new_value in *this if equal, otherwise updates expected to the value read.

Returns:

true if the existing value of *this was equal to expected and new_value was successfully stored in *this, false otherwise.

Throws:

Nothing.

Note:

The 3-parameter overload is equivalent to the 4-parameter overload with success_order==order, and failure_order==order, except that if order is std::memory_order_acq_rel, then failure_order is std::memory_order_acquire, and if order is std::memory_order_release then failure_order is std::memory_order_relaxed.

Note:

This is an atomic read-modify-write operation for the memory location comprising *this if the result is true, with memory ordering success_order, otherwise it is an atomic load operation for the memory location comprising *this with memory ordering failure_order.

Header

#include <atomic>

See Also