Почему невозможно создать атомную пару? - PullRequest
2 голосов
/ 23 мая 2019

При компиляции следующего фрагмента кода (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) я получаю:

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),

демонстрации:

Я не могу понять причину;Кто-нибудь может мне помочь, пожалуйста?

1 Ответ

8 голосов
/ 23 мая 2019

std::atomic<T> требует, чтобы T было TriviallyCopyable .

Вы не можете определить 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;
};

демо: https://godbolt.org/z/epPvOr

...