"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-17
Browse:710

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:

class A {
public:
   A(){}
   A(A &&{}){};
};

int main(int, char*) {
   A a;
   new A(a);
   return 0;
}

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:

class A {
public:
   A(){}
   A(A &&{}){};
   A(const A&{}) = default;
};

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3