Home >Backend Development >C++ >Why Does Visual Studio 2015 Report Error C2280 \'Deleted Copy Constructor\' When Compiling Move Constructor Code?

Why Does Visual Studio 2015 Report Error C2280 \'Deleted Copy Constructor\' When Compiling Move Constructor Code?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 20:01:02374browse

Why Does Visual Studio 2015 Report Error C2280

Visual Studio 2015 Reports C2280: Exploring the "Deleted Copy Constructor" Issue

In Visual Studio 2013, compiling the following code executes without errors:

<code class="cpp">class A {
public:
   A(){}
   A(A &&{}){};
};

int main(int, char*) {
   A a;
   new A(a);
   return 0;
}</code>

However, upon compilation in Visual Studio 2015 RC, the compiler raises error C2280:

1> c:\dev\foo\foo.cpp(11): error C2280: 'A::A(const A &)'
: attempting to reference a deleted function

The Reason Behind the Error

Visual Studio 2015 behaves differently than its predecessor. According to the C standard, if a class definition declares a move constructor or move assignment operator, the compiler implicitly generates a copy constructor and copy assignment operator as deleted. This is the case in the provided code snippet, where the move constructor is present.

Addressing the Problem

To resolve the compilation error, the explicit declaration of the copy constructor and copy assignment operator as default is necessary:

<code class="cpp">class A {
public:
   A(){}
   A(A &&{}){};
   A(const A&{}) = default;
};</code>

With this modification, the compiler will generate the required copy constructor and copy assignment operator without marking them as deleted.

Additional Considerations

If the class defines move semantics, it's generally recommended to also define a move assignment operator and a destructor. Following the "Rule of Five" principle can help ensure proper resource management.

The above is the detailed content of Why Does Visual Studio 2015 Report Error C2280 'Deleted Copy Constructor' When Compiling Move Constructor Code?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn