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

Why is it not possible to instantiate an atomic pair?

编译以下代码时(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 with --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),

演示:

我想不通为什么;谁能帮帮我?

std::atomic<T> requires T to be TriviallyCopyable.

您不能定义 std::atomic<std::pair<...>>,因为 std::pair 不可复制。有关详细信息,请阅读 .

作为变通方法,您可以定义自己的简化简单可复制对:

#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

以下将为您提供正确的原子对类型:

#include <atomic>
#include <iostream>
#include <thread>
#include <utility>
#include <vector>

int main() {
  std::pair<std::atomic<int>, std::atomic<int>> counterPair;
  counterPair.first.store(0);
  counterPair.second.store(0);
  std::vector<std::thread> threads;
 
  for(int i = 0; i < 2; i++) {
    threads.push_back(std::thread([&counterPair, i]() {
      for(int j = 0; j < 100; j++) {
        if((i + j) % 2 == 1) {
          counterPair.first++;
        } else {
          counterPair.second++;
        }
      }
    }));
  }

  for(auto& thread : threads) {
    thread.join();
  }

  std::cout << counterPair.first.load() << ", " << counterPair.second.load() << std::endl;

  return 0;
}

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