Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: use of deleted function ‘std::atomic<bool>::atomic(const std::atomic<bool>&)’?

Tags:

c++

This is my class structure/setup

class A {
   public:
   std::atomic_bool isStarted();
   ...
   private:
   std::atomic_bool started;
}

std::atomic_bool A::isStarted() {
    return started;
}

This all compiles fine but when I have an instance of A

and attempt to invoke a.isStarted(), I get this error

error: use of deleted function ‘std::atomic<bool>::atomic(const std::atomic<bool>&)’
 return started;
        ^~~~~~~

How should I go about restructuring the isStarted function to not invoke this deleted function? I don't understand why the copy constructor is being invoked when I'm just returning the boolean field.

like image 558
committedandroider Avatar asked Apr 16 '26 06:04

committedandroider


1 Answers

Current version returns atomic_bool by value, this will use deleted copy constructor, you can change the function to return reference to your class member, like this std::atomic_bool& A::isStarted()

From https://en.cppreference.com/w/cpp/atomic/atomic

std::atomic is neither copyable nor movable.

like image 196
ygroeg Avatar answered Apr 17 '26 20:04

ygroeg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!