在使用基于类的原子时有编译问题。
错误:将已删除的函数‘std::atomic<_Tp>::atomic()与_Tp =node’堆栈(){^
/usr/include/c++/5/atomic:185:7:注意:‘std::atomic<_Tp>::atomic() noexcept with _Tp =node’被隐式删除,因为它的异常规范与隐式异常规范‘’atomic() noexcept =default不匹配;^
#include <atomic>
#include <cstdlib>
#include <memory>
class node
{
private:
int data;
bool hasTransaction;
public:
node(int& data) : data(data), hasTransaction(true) {}
node() : data(10), hasTransaction(true) {}
};
class stack {
std::atomic<node> head;
public:
void push(int data) {
node new_node(data);
node current = head.load(std::memory_order_relaxed);
while (!head.compare_exchange_strong(
current,
new_node,
std::memory_order_release,
std::memory_order_relaxed))
;
}
stack() {
node a;
std::atomic_init(&head, a);
head.store(a);
};
};
int main()
{
stack s;
s.push(1);
s.push(2);
s.push(3);
}发布于 2019-06-30 09:39:30
这是因为您的node类型的默认构造函数没有标记为noexcept。std::atomic<T>默认构造函数被标记为noexcept,因此T的默认构造函数也必须是。
它应该是:
node() noexcept : data(10), hasTransaction(true) {}但是,您可能应该知道,除非您的类型是微不足道的,否则这种“原子”类型很可能会通过互斥使其成为线程安全的。因此,在这种情况下使用原子只会使您的工作变得更加困难,而不会有任何收获。
通常,您不希望使用atomics,除非它是用于某些原始类型(通常是原始指针或整数类型)。
https://stackoverflow.com/questions/56821864
复制相似问题