Rule of three (C programming)

The rule of three designated in the programming language C , a rule that says that if a class of one of the following three elements defined, and the other two should be defined:

  • Copy constructor
  • Destructor
  • Assignment operator

These are automatically generated by the compiler, but can be replaced with an explicitly defined by the programmer version. This is done for one of these elements, it means that the compiler-generated version of the corresponding element does not satisfy the requirements of the class. It can be concluded that this is probably also in the rest of these three elements of the case.

Reason for this occurrence is the fact that compiler-generated elements in many cases not sufficient to fulfill certain tasks, such as when the class of objects of other classes is composed exclusively used by it (composition). The compiler-generated variant copies only the pointer to the object ( shallow copy ). A manipulation of the copied object would then affect the original, since both access the same sub-objects. In such a case, the copy constructor is important to also copy the part objects ( deep copy). Similarly, the destructor is needed to delete the sub-objects also by deleting the object.

Since the release of C 11, this rule is for five rule in which also

  • Verschiebekonstruktor
  • Shift assignment

Should be defined.

294086
de