[ fromfile: autoptr.xml id: autoptr ]
A wrapper encapsulates and manages at least one other object.
If that object is a heap object, we can use the Standard Library auto_ptr to ensure that the object is destroyed when the wrapper is.
auto_ptr is a template type, so it can be instantiated for use with any other type.
In Example 17.23 we work with the Customer type.
Example 17.23. auto_ptr code fragment
for (int i=0; i< someNumber; ++i) {
auto_ptr<Customer> custPtr;
auto_ptr<Customer> custPtr2 (new Customer());
custPtr = custPtr2;
}
The loop is here to demonstrate how a block of code creates and destroys its local objects on the stack. | |
a null | |
| |
| |
At the end of each iteration, the local |
An auto_ptr<Customer> is type-restricted to point to objects derived from Customer, as specified in the template parameter. An attempt to use this to point to any other type will result in a compiler error.
When an auto_ptr is destroyed, the pointed-to heap object is deleted. Therefore, when the code in Example 17.23 is executed, there will be no memory leaks, even though the loop created many new heap objects, and the code contains no corresponding delete.
Assignment with auto_ptr is very different from assignment between other types. Usually, the right side is not changed. However, the auto_ptr on the right side of an assignment always becomes NULL, while the left side takes ownership of the pointed-to object. This guarantees that only one auto_ptr is ever pointing to an object and ensures that the object will get deleted exactly once by its auto_ptr.
Smart pointers such as the auto_ptr are frequently used in wrappers and façades, as we show in the next example.
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |