C++ Compiler Error C2280 “attempting to reference a deleted function” in Visual Studio 2013 and 2015

后端 未结 7 1013
误落风尘
误落风尘 2020-11-27 18:03

This snippet is compiled without errors in Visual Studio 2013 (Version 12.0.31101.00 Update 4)

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

int main(i         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 19:00

    From [class.copy]/7, emphasis mine:

    If the class definition does not explicitly declare a copy constructor, a non-explicit one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.

    There is an equivalent section with similar wording for copy assignment in paragraph 18. So your class is really:

    class A
    {
    public:
       // explicit
       A(){}
       A(A &&){}
    
       // implicit
       A(const A&) = delete;
       A& operator=(const A&) = delete;
    };
    

    which is why you can't copy-construct it. If you provide a move constructor/assignment, and you still want the class to be copyable, you will have to explicitly provide those special member functions:

        A(const A&) = default;
        A& operator=(const A&) = default;
    

    You will also need to declare a move assignment operator. If you really have a need for these special functions, you will also probably need the destructor. See Rule of Five.

提交回复
热议问题