1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
Four important extensions to classes were introduced in this chapter: the
destructor, the copy constructor, the move constructor and
the overloaded assignment operator. In addition the importance of
em(swapping), especially in combination with the overloaded assignment
operator, was stressed.
Classes having pointer data members, pointing to dynamically allocated memory
controlled by the objects of those classes, are
potential sources of memory leaks. The extensions introduced in this
chapter implement the standard defense against such memory leaks.
Encapsulation (data hiding) allows us to ensure that the object's data
integrity is maintained. The automatic activation of constructors and
destructors greatly enhance our capabilities to ensure the data integrity of
objects doing dynamic memory allocation.
A simple conclusion is therefore that classes whose objects allocate memory
controlled by themselves must at least implement a
em(destructor), an em(overloaded assignment operator) and a
em(copy constructor). Implementing a em(move constructor) remains
optional, but it allows us to use em(factory functions) with classes em(not)
allowing copy construction and/or assignment.
In the end, assuming the availability of at least a copy or move constructor,
the compiler might avoid them using em(copy elision). The compiler is free to
use copy elision wherever possible; it is, however, never a requirement. The
compiler may therefore always decide not to use copy elision. In all
situations where otherwise a copy or move constructor would have been used the
compiler may consider to use copy elision.
|