Visual Studio 2013 compiles the following code snippet without errors:
<code class="cpp">class A { public: A(){} A(A &&){} }; int main(int, char*) { A a; new A(a); return 0; }</code>
However, Visual Studio 2015 RC encounters error C2280:
1>c:\dev\foo\foo.cpp(11): error C2280: 'A::A(const A &)': attempting to reference a deleted function 1> c:\dev\foo\foo.cpp(6): note: compiler has generated 'A::A' here
In C 11, if a class definition does not explicitly declare a copy constructor, the compiler implicitly generates one. However, if the class defines a move constructor or move assignment operator without also providing an explicit copy constructor, the implicit copy constructor is defined as =delete. This is to enforce the Rule of Five, which prevents unintentional slicing when copying objects between different base and derived classes.
To resolve the C2280 error, you must explicitly declare the copy constructor if you want the class to be copyable. Here are two options:
Explicitly define and delete the copy constructor:
<code class="cpp">class A { public: explicit A(){} A(A &&){} A(const A&) = delete; };</code>
Explicitly provide and default the copy constructor:
<code class="cpp">class A { public: explicit A(){} A(A &&){} A(const A&) = default; A& operator=(const A&) = default; };</code>
In the second approach, you also need to explicitly provide a move assignment operator, and consider declaring a destructor to follow the Rule of Five.
The above is the detailed content of Why Am I Getting Compiler Error C2280: \'Attempting to Reference a Deleted Function\' in Visual Studio?. For more information, please follow other related articles on the PHP Chinese website!