Home > Backend Development > C++ > Why Am I Getting Compiler Error C2280: \'Attempting to Reference a Deleted Function\' in Visual Studio?

Why Am I Getting Compiler Error C2280: \'Attempting to Reference a Deleted Function\' in Visual Studio?

Linda Hamilton
Release: 2024-10-27 10:31:03
Original
498 people have browsed it

Why Am I Getting Compiler Error C2280:

Compiler Error C2280: Resolving "Attempting to Reference a Deleted Function" in Visual Studio

The Issue

Visual Studio 2013 compiles the following code snippet without errors:

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

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

However, Visual Studio 2015 RC encounters error C2280:

1>c:\dev\foo\foo.cpp(11): error C2280: 'A::A(const A &amp;)': attempting to reference a deleted function
1>  c:\dev\foo\foo.cpp(6): note: compiler has generated 'A::A' here
Copy after login

Cause

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.

Solution

To resolve the C2280 error, you must explicitly declare the copy constructor if you want the class to be copyable. Here are two options:

  1. Explicitly define and delete the copy constructor:

    <code class="cpp">class A {
    public:
       explicit A(){}
       A(A &amp;&amp;){}
       A(const A&amp;) = delete;
    };</code>
    Copy after login
  2. Explicitly provide and default the copy constructor:

    <code class="cpp">class A {
    public:
       explicit A(){}
       A(A &amp;&amp;){}
       A(const A&amp;) = default;
       A&amp; operator=(const A&amp;) = default;
    };</code>
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template