0

Consider the following program, named atomic_return.cpp

#include <stdio.h>
#include <atomic>

using namespace std;

class Stats
{
    atomic_ullong stats[10] = {};
  public:

    atomic_ullong get_stat(int index) { return stats[index]; }
};

int main()
{
    Stats stat_obj;

    stat_obj.get_stat(1);

    return 0;
}

I get the following error when I compile:

g++ atomic_return.cpp -o atomic_return
atomic_return.cpp: In member function ‘std::atomic_ullong Stats::get_stat(int)’:
atomic_return.cpp:11:59: error: use of deleted function ‘std::atomic<long long unsigned int>::atomic(const std::atomic<long long unsigned int>&)’
   11 |     atomic_ullong get_stat(int index) { return stats[index]; }
      |                                                           ^
In file included from atomic_return.cpp:2:
/usr/include/c++/9/atomic:870:7: note: declared here
  870 |       atomic(const atomic&) = delete;
      |       ^~~~~~

Why can I not a return an atomic_ullong? I am not able to make sense of the error.

rzambre
  • 1
  • 2
  • 2
    Does this answer your question? https://stackoverflow.com/questions/15249998/why-are-stdatomic-objects-not-copyable – Drew Dormann Sep 02 '21 at 21:39
  • 8
    Why exactly are you trying to return a copy of an atomic variable? That in itself makes no real sense. You would normally want to either return a reference to it or the value of the atomic – UnholySheep Sep 02 '21 at 21:41
  • Decoding the error message `error: use of deleted function ‘std::atomic<...>::atomic(const std::atomic<...>&)’` says the `atomic` copy constructor has been "deleted". This is done to prevent copying. `atomic_ullong get_stat(int index) { return stats[index]; }` shows where your code tried to make the copy. The `atomic(const atomic&) = delete;` shows you exactly what is in the code preventing the copy. – user4581301 Sep 02 '21 at 22:30
  • "Why can I not a return an atomic_ullong?" because it makes no sense to return a copy of `std::atomic` – Slava Sep 02 '21 at 23:08
  • Thank for the pointers! Will return a reference to it. – rzambre Sep 03 '21 at 22:27

0 Answers0