Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the move constructor defined and the assignment operator implicitly deleted?

Tags:

c++

gcc

c++11

g++

struct Foo
{
    Foo() = default;
    Foo(Foo&&) = default;
};

int main()
{
    Foo a, b;
    a = b;
   // ^ 

   return 0;
}

error: use of deleted function 'Foo& Foo::operator=(const Foo&)'

in g++4.6 -std=c++0x it's ok. but, in g++6.2 -std=c++11 it's error. why?

like image 813
Bruce Avatar asked Dec 11 '22 11:12

Bruce


1 Answers

The answer is because the C++ standard says so:

[class.copy]

If the class definition does not explicitly declare a copy constructor, 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).

You can always declare a default copy constructor, in your case:

 Foo(const Foo&) = default;
like image 109
Sam Varshavchik Avatar answered May 08 '23 05:05

Sam Varshavchik