error: use of deleted function ‘std::atomic<_Tp>::atomic() [with _Tp = node]’

Viewed 1745

Having compile issue when using atomic with class based.

error: use of deleted function ‘std::atomic<_Tp>::atomic() [with _Tp = node]’ stack() { ^

/usr/include/c++/5/atomic:185:7: note: ‘std::atomic<_Tp>::atomic() noexcept [with _Tp = node]’ is implicitly deleted because its exception-specification does not match the implicit exception-specification ‘’ 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);
}
1 Answers

It's because your node type's default constructor is not marked noexcept. The std::atomic<T> default constructor is marked as noexcept, so T's default constructor must also be.

It should read:

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

However, you should probably know that unless your type is trivial, this "atomic" type will likely be made thread-safe via mutex. Thus, using atomics in this case is only making your life harder for no gain.

Typically you wouldn't want to use atomics unless it was for some primitive type (usually a raw pointer or an integer type).

Related