为什么不可能实例化一个原子对?

hex*_*ecs 2 c++ std-pair stdatomic

编译以下代码时(gcc-4.8,--std=c++11):

#include <atomic>
#include <utility>
#include <cstdint>

struct X {
    std::atomic<std::pair<uint32_t, uint32_t>> A;
};
Run Code Online (Sandbox Code Playgroud)

我收到以下编译错误:

/usr/local/include/c++/4.8.2/atomic:167:7: error: function
 'std::atomic<_Tp>::atomic() [with _Tp = std::pair<unsigned int, unsigned int>]'
 defaulted on its first declaration with an exception-specification that differs
 from the implicit declaration 'constexpr std::atomic<std::pair<unsigned int, 
unsigned int> >::atomic()'
Run Code Online (Sandbox Code Playgroud)

使用较新的编译器(带有的gcc-9 --std=c++17),我得到:

In instantiation of 'struct std::atomic<std::pair<int, int> >':
  error: static assertion failed: std::atomic requires a trivially copyable type
static_assert(__is_trivially_copyable(_Tp),
Run Code Online (Sandbox Code Playgroud)

演示:

我不知道为什么。有人可以帮我吗?

YSC*_*YSC 8

std::atomic<T>要求TTriviallyCopyable

您不能定义一个std::atomic<std::pair<...>>因为std::pair无法复制的。有关此的更多信息,请阅读为什么std :: tuple不能被普通复制?

作为解决方法,您可以定义自己的简化的可复制对:

#include <atomic>
#include <cstdint>

struct X
{
    using pair = struct { std::uint32_t first; std::uint32_t second; };
    std::atomic<pair> A;
};
Run Code Online (Sandbox Code Playgroud)

演示:https : //godbolt.org/z/epPvOr