原子结构的统一初始化

Uniform initialization of an atomic struct?

本文关键字:初始化 原子结构      更新时间:2023-10-16
struct S
{
    int x;
    int y;
};
std::atomic<S> asd{{1, 2}}; // what should this be? This doesn't work

编辑:{{1, 2}}({1, 2})都在g++中工作,都不能在clang中工作。有解决clang的方法吗?

这是clang bug 18097。这里有一个讨论这个问题的长线程,这似乎是clang只支持atomic<T>T的标量类型。c++ 11标准明确规定(§29.5/1)T可以是任何平凡的可复制类型。

问题中显示的两种用法都应该匹配这个构造函数

constexpr atomic(T) noexcept;

我能想到的解决这个问题的唯一方法是默认构造atomic<S>,然后使用atomic::store初始化对象。

std::atomic<S> asd;
asd.store({1,2});

std::atomic<S> asd({1, 2});

std::atomic<S>有一个接受S类型值的构造函数。由于这个构造函数,初始化列表{1,2}被隐式地转换为临时S。