Error C2280: Attempting to reference a remote function (atomic <int>)

I have class A with a member variable _atomicVar type std::atomic<int> .

 #include <atomic> class A { public: A(); ~A(); private: std::atomic<int> _atomicVar; }; 

If I create a project, I get the following error:

 error C2280: 'std::atomic<int>::atomic(const std::atomic<int> &)' : attempting to reference a deleted function 

I am basically a C # developer, so I don't know every detail of C ++ (yet). I do not know where I am using the c'tor atomic<int> copy.
I also tried to initialize _atomicVar :

 std::atomic<int> _atomicVar { 0 }; 

... but that didn't work.
I would expect _atomicVar (without explicit initialization) to get initialized with the default value for int .
Can you tell me why this error occurs?

+6
source share
1 answer

This is because the copy constructor std::atomic has been removed .

See this documentation page .

Since you do not define an explicit copy constructor for A , the compiler generates a default one, which simply calls copy constructors for all members (which is not valid for std::atomic ).

Decision:

 class A { public: A(); A(const A& origin); // add this line ~A(); private: std::atomic<int> _atomicVar; }; A::A(const A& origin) : _atomicVar(0) //zero-initialize _atomicVar { } 

EDIT

If you are wondering why atomic types cannot be copied, you can read this question , especially the accepted answer. If you want to copy the value of std::atomic , you can do this:

 A::A(const A& origin) : _atomicVar(origin._atomicVar.load()) { } 

But keep in mind that this operation alone will not be atomic (and, for most logics, meaningless).

In addition, you can also specify an explicit assignment operator (remember the Rule of Three ).

The best option for the correct behavior of your program would be to remove these two methods:

 class A { public: A(); A(const A&) = delete; ~A(); A& operator=(const A&) = delete; private: std::atomic<int> _atomicVar; }; 

If your compiler does not support this (for example, any VC before VC12), declare them closed and do not provide the body:

 class A { public: A(); ~A(); private: //do not define these two A(const A&); A& operator=(const A&); private: std::atomic<int> _atomicVar; }; 
+14
source

Source: https://habr.com/ru/post/984395/


All Articles