为什么不可能实例化原子对
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()'
使用了最新的编译器(带有--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
相关文章:
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 函数在可变参数模板的实例化期间不可见
- 为什么我们不在下面给出的代码中使用指针来实例化C++的实体对象?
- 为什么显式模板实例化不会破坏 ODR?
- 需要实例化不同类/对象并在启动时确定的硬件插槽的设计模式
- 为什么显式模板实例化不起作用
- unique_ptr 使用尚未定义的参数进行实例化不会导致错误
- 为什么显式模板实例化不起作用?
- C++标准是否明确允许/禁止实例化不完整类型的 std::函数?
- 为什么不可能实例化原子对
- 模板函数是否以内联方式声明 constexpr,即使实例化不是 constexpr
- 编译的程序是否有可能不包含实例化的模板类
- 模板专用化的实例化不正确
- 为什么很清楚模板函数实例化不会内联
- 为什么这些函数模板中的任何一个都与实例化不匹配?
- 模板实例化不"do inheritance"
- Wykobi -错误:显式实例化不能使用' inline '说明符[-fpermissive]
- 当实例化是可能的,但在c++中不能继承时