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

时间:2019-05-23 12:38:55

标签: 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;
};

使用更新的编译器(带有/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()' 的gcc-9),我得到:

--std=c++17

演示:

我不知道原因。有人可以帮我吗?

1 个答案:

答案 0 :(得分:8)

std::atomic<T>要求TTriviallyCopyable

您无法定义std::atomic<std::pair<...>>,因为std::pair不可复制。有关更多信息,请阅读Why can't std::tuple be trivially copyable?

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

#include <atomic>
#include <cstdint>

struct X
{
    using pair = struct { std::uint32_t first; std::uint32_t second; };
    std::atomic<pair> A;
};

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

相关问题