CKTIS / C++
std::atomic_ref: atomic operations on an existing object
std::atomic_ref creates a non-owning atomic view of an existing trivially copyable object.
Version: C++23
Syntax
template<class T>
struct atomic_ref;
static constexpr std::size_t required_alignment = implementation-defined;
explicit atomic_ref(T& object);
T load(std::memory_order order = std::memory_order_seq_cst) const noexcept;
void store(T desired, std::memory_order order = std::memory_order_seq_cst) const noexcept;
// applicable numeric and pointer specializations additionally provide:
T fetch_add(/* difference type */ operand,
std::memory_order order = std::memory_order_seq_cst) const noexcept;std::atomic_ref<T> from <atomic> owns no value: it binds to an existing T and performs load, store, exchange, compare-exchange, and type-appropriate read-modify-write operations on it. The referenced object must outlive every view that refers to it.
T must be trivially copyable and the object address must satisfy atomic_ref<T>::required_alignment. While any such view exists, every access to the complete object must occur exclusively through compatible atomic_ref instances; a competing ordinary read or write violates the contract. std::atomic_ref::required_alignment gives the required alignment of an object that the view will reference. On an applicable numeric or pointer specialization, std::atomic_ref::fetch_add atomically adds its operand as one read-modify-write operation and returns the previous value.
The view is copyable but cannot be rebound by assignment. Its operations need not be lock-free; query is_lock_free(). The default memory order is std::memory_order_seq_cst, while weaker orders require a correct synchronization protocol.
Examples
#include <atomic>
#include <iostream>
int main() {
alignas(std::atomic_ref<int>::required_alignment) int value = 3;
std::atomic_ref<int> view{value};
view.fetch_add(4);
std::cout << view.load() << '\n';
}
Result
7
std::atomic_ref → 7