gpt4 book ai didi

c++ - 错误 : use of deleted function ‘std::atomic<_Tp>::atomic() [with _Tp = node]’

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:43 26 4
gpt4 key购买 nike

在基于类的情况下使用 atomic 时出现编译问题。

错误:使用已删除的函数‘std::atomic<_Tp>::atomic() [with _Tp = node]’ 堆() { ^

/usr/include/c++/5/atomic:185:7: 注意:'std::atomic<_Tp>::atomic() noexcept [with _Tp = node]' 被隐式删除,因为它的异常规范确实不匹配隐式异常规范 '' atomic() noexcept = 默认值; ^

#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);
}

最佳答案

那是因为你的node类型的默认构造函数未标记 noexcept . std::atomic<T>默认构造函数被标记为 noexcept,所以 T的默认构造函数也必须是。

它应该是:

node() noexcept : data(10), hasTransaction(true) {}

但是,您可能应该知道,除非您的类型很简单,否则这种“原子”类型可能会通过互斥锁实现线程安全。因此,在这种情况下使用原子只会让你的生活更加艰难,没有任何收获。

通常您不会希望使用原子,除非它用于某些基本类型(通常是原始指针或整数类型)。

关于c++ - 错误 : use of deleted function ‘std::atomic<_Tp>::atomic() [with _Tp = node]’ ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56821864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com