简体   繁体   中英

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

在定义定制的析构函数时,C ++标准委员会选择删除隐式定义的移动赋值运算符的理由是什么?

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.

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 = default ed implementation. The class clearly already does something special (otherwise there would be no destructor) anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM