Classes Whose Constructors Use new
You need to take several precautions when designing classes that use the new
operator to allocate memory pointed to by a class member (yes, we summarized these precautions recently, but the rules are very important to remember, particularly because the compiler does not know them and thus won’t catch your mistakes):
• Any class member that points to memory allocated by new
should have the delete
operator applied to it in the class destructor. This frees the allocated memory.
• If a destructor frees memory by applying delete
to a pointer that is a class member, every constructor for that class should initialize that pointer, either by using new
or by setting the pointer to the null pointer.
• Constructors should ...
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.