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

Why is it not possible to instantiate an atomic pair?

本文关键字:实例化 不可能 为什么      更新时间:2023-10-16

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

使用了最新的编译器(带有--std=c++17的GCC-9(,我得到了:

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

演示:

  • https://godbolt.org/z/ozhwuq
  • https://godbolt.org/z/tfkg5f

我不知道原因;谁能帮我吗?

std::atomic<T>要求 T trivallycopyable

您无法定义std::atomic<std::pair<...>>,因为std::pair不是微不足道的共配。有关此信息的更多信息,请阅读为什么STD ::元组可以琐碎地复制?

作为解决方法,您可以定义自己的简化琐碎的共配对:

#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