In most cases, classes that execute dynamic memory allocation use new to allocate memory in the constructor, and then delete to release memory in the destructor. It is certainly not difficult to write this class at the beginning. You will remember to use delete for all the members allocated with memory in all constructors.
However, after the class is maintained and upgraded, the situation becomes difficult, because the programmer who modifies the class code is not necessarily the first person to write the class. Adding a pointer member means almost all of the following work is required:
· Initialize the pointer in each constructor. For some constructors, if there is no memory to allocate to the pointer, the pointer should be initialized to 0 (that is, a null pointer ).
· Delete the existing memory and assign it to the new memory of the pointer through the value assignment operator.
· Delete the pointer in the destructor.
If you forget to initialize a pointer in the constructor or forget to process it during the value assignment operation, the problem will appear very fast and obvious, in practice, these two problems will not affect you. However, if the pointer is not deleted in the destructor, it does not show obvious external symptoms. On the contrary, it may only show a small amount of memory leakage, and continues to grow. In the end, it swallowed up your address space, leading to program failure. Because this situation is often less noticeable, you must note it clearly when adding a pointer member to the class.
In addition, deleting a null pointer is safe (because it does not do anything ). Therefore, when writing constructors, value assignment operators, or other member functions, each pointer member of the class either points to a valid memory or points to null, in your destructor, you can simply delete them without worrying about whether they have been replaced by new ones.
Of course, do not use these terms absolutely. For example, you certainly won't use Delete to delete a pointer that does not use new for initialization, and you don't have to delete it when using smart pointer objects, you will never delete a pointer that is passed to you. In other words, unless the class members use new, they do not need to use Delete in the destructor.
Speaking of smart pointers, this article introduces a method to avoid having to delete pointer members, that is, replacing these Members with smart pointer objects, such as auto_ptr in the C ++ standard library.