Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why defining a destructor deletes the implicitly defined move assignment operator?

What is the rationale behind the C++ Standard Committee choice of deleting the implicitly defined move assignment operator when a customized destructor is defined?

like image 590
nyarlathotep108 Avatar asked Dec 02 '15 12:12

nyarlathotep108


2 Answers

From Scott Meyer's Effective Modern C++ Item 17 (assuming you have knowledge of the Rule of Three):

A consequence of the Rule of Three is that the presence of a user-declared destructor indicates that simple memberwise copy is unlikely to be appropriate for the copying operations in the class. That, in turn, suggests that if a class declares a destructor, the copy operations probably shouldn't be automatically generated, because they wouldn't do the right thing. [...]

The reasoning behind the Rule of Three remains valid, however and that, combined with the observation that declaration of a copy operation precludes the implicit generation of the move operations, motivates the fact that C++11 does not generate move operations for a class with a user-declared destructor.

like image 131
TartanLlama Avatar answered Sep 21 '22 07:09

TartanLlama


The idea is that the presence of any of the default-generated structors (copy constructor, copy assignment, or destructor) indicates that a type needs to do some sort of special resource management. If that is the case, the default move operations may not do the Right Thing. I'm not sure if actually failing examples where the default generated copy constructor works correctly but the default generated move constructor failed were presented.

The resolution was that it is safer to not generate the move operations by default, especially as it is easy to ask for the respective move operations: simply add a = defaulted implementation. The class clearly already does something special (otherwise there would be no destructor) anyway.

like image 45
Dietmar Kühl Avatar answered Sep 22 '22 07:09

Dietmar Kühl