Effective C ++ 2e Item6

zhaozj2021-02-11  236

Terms 6: Calling Delete for pointer members in the destructor

In most cases, the classes that perform dynamic memory allocation are allocated in the constructor, and the memory is allocated with New, and then releases memory with delete in the destructor. When you first write this class, it is of course not difficult, you will remember that all members allocated in all constructed functions use DELETE.

However, this class has been maintained and upgraded, and the situation will become difficult, because the programmer for modification of class code is not necessarily the earliest to write this class. Increases a pointer member means almost all the following work: • Initialize the pointer in each constructor. For some constructor, if there is no memory to be assigned to the pointer, the pointer is initialized to 0 (ie, the null pointer). · Delete existing memory and assign a new memory by assigning the operator. · Remove the pointer in the destructor.

If you forget to initialize a pointer in the constructor, or forget it in the process of assignment, the problem will appear very fast, it is obvious, so these two questions in practice will not torture you. However, if the pointer is not deleted in the destructor, it does not show great external symptoms. Instead, it may only be characterized by a little slight memory leak, and growing, and finally engraving your address space, causing the program to abort. Because this situation is often not so attacked, it must be referred to each time a pointer member is added to the class.

In addition, deleting an empty pointer is safe (because it doesn't do anything). So, when writing constructor, assigning operators, or other member functions, each pointer member of the class either points to a valid memory, or point to the empty, then you can use only simple Delete in your destructor. Drop them, don't worry, they are too many.

Of course, don't use the use of this terms. For example, you certainly don't delete a pointer that is not initialized with New, and you will never delete a pointer to you when you use smart to delete it. In other words, unless the class member originally used New, it is not necessary to use Delete in the destructor.

Speaking of intelligent pointers, here is introduced to avoid the method of deleting a pointer member, that is, replacing these members with intelligent pointer, such as Auto_PTR in the C standard library. Want to know how it works, look at the Terms M9 and M10.

转载请注明原文地址:https://www.9cbs.com/read-4479.html

New Post(0)