std::atomic_ref是C++20引入的对已存在且满足对齐、生命周期和类型要求的变量提供原子访问的非拥有式引用;它不能直接用于任意变量,因必须同时满足alignof(T)对齐、变量生命周期不短于atomic_ref、T为平凡可复制且无冲突自定义对齐三个前提,否则触发未定义行为。
std::atomic_ref 是 C++20 引入的工具,它不拥有内存,而是对**已存在、满足对齐和生命周期要求的变量**提供原子访问视图。它不是“把普通变量变原子”,而是“临时以原子方式操作一个合规变量”。常见误用是拿栈上未对齐的 int x; 直接构造 std::atomic_ref —— 这会触发未定义行为(UB),编译器可能不报错,但运行时可能崩溃或产生竞态。
要安全使用 std::atomic_ref,目标变量必须同时满足:
alignof(T) 对齐。例如 int 通常需 4 字节对齐,std::atomic_ref 构造时若传入 char buf[4]; int* p = reinterpret_cast(buf + 1); 就非法std::atomic_ref 的生存期不能超过所引用变量的生存期。不能对函数局部变量取 atomic_ref 后返回或存储到全局T 必须是 trivially_copyable,且不能是带 [[gnu::aligned]] 或 _Alignas 的自定义对齐类型(除非对齐值恰好匹配 alignof(T))最稳妥的方式是显式控制对齐和生命周期。以下是在 C++20 下可行的写法:
alignas(int) static int shared_counter = 0; // 强制按 int 对齐 std::atomic_ref
ref{shared_counter}; ref.fetch_add(1, std::memory_order_relaxed); // 安全
堆上分配也需注意对齐:
auto ptr = std::aligned_alloc(alignof(int), sizeof(int)); int* p = static_cast(ptr); new(p) int{42}; std::atomic_ref ref{*p}; // OK,前提是 aligned_alloc 成功且对齐达标 // ... 使用后 p->~int(); std::free(ptr);
遇到以下情况,std::atomic_ref 不是解法,应换思路:
struct S { int a; char b; };,字段 a 可能不对齐(如 b 在前导致 a 偏移为 1)。此时应改用 std::atomic 字段,或重排结构体加 alignas
int local = 0; 绝对不可传给 std::atomic_ref 并在线程间传递 —— 栈帧销毁后引用即悬空std::atomic<:optional>> 等间接方式(代价更高)真正容易被忽略的是:即使编译通过、测试通过,只要对齐或生命周期不满足,std::atomic_ref 就是 UB —— 它不提供运行时检查,也不抛异常。