Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Why should C++ keep the consistency of the default operation?

Shulou Source: shulou.com Published: 2022-06-01 19:11:50 11月16日 Update

This article mainly introduces "why C++ should maintain the consistency of the default operation". In daily operation, I believe many people have doubts about why C++ should maintain the consistency of the default operation. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the question of "why C++ should maintain the consistency of the default operation". Next, please follow the editor to study!

C.22: keep the default operation consistent

Reason (reason)

The default operation is conceptually a tightly coordinated set of processing. Their semantics are interrelated. Users will be surprised if copy / move constructions and copy / move assignments do logically different things; users will be surprised if constructors and destructors do not provide a consistent idea for resource management; users will be surprised if copy and move operations do not correspond to constructors and destructors.

Example, bad (negative example)

Class Silly {/ / BAD: Inconsistent copy operations

Class Impl {

/ /...

}

Shared_ptr p

Public:

Silly (const Silly& a): P {a.p} {* p = * a.p;} / / deep copy

Silly& operator= (const Silly& a) {p = a.p;} / / shallow copy

/ /...

}

These operations (copy construction and assignment) have different semantics about the copy (deep copy and shallow copy). This can lead to confusion and mistakes.

Enforcement (implementation recommendations)

Tags: Copy function move variable member consistency Clearing complexity Learning surprise user different more semantics operator help Operation rigorous practical consistent Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Linux Microsoft Xiaomi Huawei