Clause 7: when using a new pointer container, remember to delete the pointers before destroying the container.
The containers in STL are excellent. They provide pre-and reverse traversal iterators (through begin, end, rbegin, etc.); they can tell you the type of the object to be accommodated (through typedef of value_type ); during insertion and deletion, they are responsible for any memory management required; they report the number of objects and the maximum number of objects that can be accommodated (by size and max_size, respectively ); of course, when the container is destroyed, each object is automatically destroyed.
With such a smart container, many programmers no longer worry about clearing their jobs after use. They said their containers would help them solve the problem. In many cases, they are right, but when the container holds a pointer to an object allocated through new, they are wrong. Indeed, when a pointer container is destroyed, every element contained in it (that container) will be destroyed, but the pointer's "destructor" is not operational! It certainly does not call Delete.
As a result, the following code directly causes a memory leak:
Void dosomething () {vector <widget *> VWP; For (INT I = 0; I <some_magic_number; ++ I) VWP. push_back (new widget );... // use VWP} // widgets leaked here!
After VWP exists, every element of VWP is destroyed, but it does not change the fact that deleting is never applied to the new object. Such deletion is your responsibility, not vector. This is a feature. Only you know whether a pointer isShouldDeleted.
Generally, you need to delete them. When the situation is as follows, it can be easily implemented:
Void dosomething () {vector <widget *> VWP;... // same as for (vector <widget *>: iterator I = VWP. Begin (); I! = VWP. End (), ++ I) {Delete * I ;}}
This can work, unless you are not very picky about your "work. One problem is that the new for loop code is much more than for_each, but it is not clear with for_each (See Clause 43 ). Another problem is that this code is not exceptionally secure. If an exception is thrown between filling VWP with pointers and deleting them, resource leakage occurs again. Fortunately, both problems can be overcome.
To convert your for_each-like loop into using for_each, you need to transfer Delete to a function object. This is as simple as a child. Suppose you have a child who likes to play with STL:
Template <typename T> struct deleteobject: // Clause 40 describes why public unary_function <const T *, void >{// this inherits void operator () (const T * PTR) const {Delete PTR ;}};
Now you can do this:
Void dosomething () {... // same as for_each (VWP. Begin (), VWP. End (), deleteobject <widget> );}
Unfortunately, this allows you to specify the type of the object that deleteobject will delete (in this example, it is a widget ). That's annoying. VWP is a vector <widget *>, so of course deleteobject will delete the widget * pointer! Success! This type of redundancy is not annoying, because it can cause bugs that are hard to be tracked. Suppose, for example, some people intentionally inherit from string:
class SpecialString: public string { ... };
This is a very dangerous behavior, because string, like all standard STL containers, lacks virtual destructor, class public inheritance without virtual destructor is a big C ++ taboo. (For more information, see any good C ++ books. In Objective C ++, Clause 14 is required .) However, there are still some people doing this, so let's consider the behavior of the code below:
Void dosomething () {deque <specialstring *> dssp;... for_each (dssp. Begin (), dssp. End (), // The behavior is not defined! You can delete a derived object without the deleteobject <string> (); // basic class of the virtual destructor} // pointer.
Note that dssp is declared to hold the specialstring * pointer, but the author of The for_each loop tells deleteobject that it will delete the string * pointer. It is easy to know what kind of errors will occur. Specialstring is similar to string, so if its users occasionally forget that they use specialstrings instead of string, they can forgive.
You can use the compiler to infer the type of pointer passed to deleteobject: Operator () to eliminate this error (also reduce the number of times that the deleteobject user needs to strike keys ). All we need to do is move templated from deleteobject to its operator ():
Struct deleteobject {// Delete the template and base class template <typename T> // templated void operator () (const T * PTR) const {Delete PTR ;}}
The compiler knows the type of the pointer passed to deleteobject: Operator (), so we can let it automatically instantiate an operator () through the pointer type (). This kind of deduction decline allows us to discard the ability to adapt deleteobject (see article 40 ). Think about the design purpose of deleteobject. It is hard to imagine that it will be a problem.
The new version of deleteobject is used. The customer code for specialstring looks like this:
Void dosomething () {deque <specialstring *> dssp;... for_each (dssp. Begin (), dssp. End (), deleteobject (); // ah! Well-defined behavior !}
Straightforward and type-safe, as we like.
But it is still not exceptionally safe. If specialstring is new but an exception is thrown before for_each is called, a leak occurs. That problem can be solved in multiple ways, but the simplest possibility is to use a smart pointer container to replace the pointer container. A typical example is to reference the counting pointer. (If you are not familiar with the concept of smart pointers, you can find descriptions in any intermediate or advanced C ++ books. In more than tive C ++, this section is in Clause 28 .)
STL itself does not contain reference counting pointers, and writing a good one -- a job that always works correctly -- requires a skill, unless necessary, you must not do it. I published the code used to reference the counting smart pointer in "more effective C ++" in 1996, although it was implemented based on the developed smart pointer and submitted to experienced developers for a lot of pre-release checks, the small bug report lasted for many years. The number of different methods of smart pointer errors is worth noting .)
Fortunately, you do not need to write it yourself, because the tested implementation is not hard to find. Such a smart pointer is shared_ptr In the boost library. With boost shared_ptr, the original examples of the terms can be rewritten as follows:
Void dosomething () {typedef boost: Shared _ PTR <widget> spw; // spw = "shared_ptr // to widget" vector <spw> VWP; for (INT I = 0; I <some_magic_number; ++ I) VWP. push_back (spw (new widget); // create a spw from a widget, // then perform a push_back... // use VWP} // No widget leakage or even an exception is thrown in the above Code
The silly idea you don't have is that you can create auto_ptr containers to form a pointer that can be automatically deleted. It is a terrible idea and dangerous. I discussed in Clause 8 why you should avoid it.
All we need to remember is that STL containers are intelligent, but they are not intelligent enough to know whether to delete the pointers they contain. When you want to delete the pointer container, to avoid resource leakage, you must use smart reference to count pointer objects (such as boost shared_ptr) instead of pointers, or you must manually delete each pointer in the container before the container is destroyed.
Finally, you may think that a structure similar to deleteobject can simplify the process of avoiding container resource leaks that hold object pointers, is it possible to create a deletearray struct similar to this structure to avoid container resource leakage that can accommodate pointers to arrays? Of coursePossibleBut whether it is wise is not the same thing. Clause 13 explains why the Dynamic Allocation of arrays is almost always inferior to vector and string objects. So before you write deletearray, take a look at clause 13. If you are lucky, you will know that deletearray is a struct that will never appear.