std::atomic
模板的一般版本有一个值构造函数声明为
constexpr atomic( T desired );
(参见 here )
据说模板的bool
、积分和指针特化有(引自cppreference)
standard layout, trivial default constructors, and trivial destructors. They support aggregate initialization syntax.
这是有道理的,因为只有普通默认构造函数和 dtor(即没有值构造函数)的类有资格作为聚合,因此支持聚合初始化语法。但是,以下代码在 GCC 和 clang 上都可以正常编译:
std::atomic_int i(9);
这意味着应该存在一个值构造函数。这是否违反了标准?
引用自C++11标准
These specializations shall have standard layout, trivial default constructors, and trivial destructors. They shall each support aggregate initialization syntax.
这也没有说明此类特化是否应该具有值(value)主体。
最佳答案
标准根据 [atomics.types.generic] 规定了一些类型定义:
There shall be named types corresponding to the integral specializations of atomic, as specified in Table 146, and a named type
atomic_bool
corresponding to the specifiedatomic<bool>
. Each named type is either atypedef
to the corresponding specialization or a base class of the corresponding specialization. If it is a base class, it shall support the same member functions as the corresponding specialization.
在表 146 中,我们看到 atomic_int
是 atomic<int>
的类型定义. integral 特化在同一节中定义为:
template <> struct atomic<integral > {
...
constexpr atomic(integral ) noexcept;
...
};
代入 int
对于积分,我们有一个constexpr atomic_int(int )
构造函数。坦率地说,如果您不能初始化 atomic<T>
会很奇怪用T
...
关于c++ - std::atomic 的标准特化不应该缺少值构造函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29761513/