Previous fileTop of DocumentContentsIndex pageNext file
Apache C++ Standard Library User's Guide

19.2 Declaration and Initialization of Autopointers

You attach an auto_ptr object to a pointer either by using one of the constructors for auto_ptr, by assigning one auto_ptr object to another, or by using the reset member function. Only one auto_ptr owns a particular pointer at any one time, except for the null pointer, which all auto_ptrs own by default. Any use of the auto_ptr copy constructor or assignment operator transfers ownership from one auto_ptr object to another. For instance, suppose we create an auto_ptr a like this:

The auto_ptr object a now owns the newly created pointer. When a is destroyed, such as when it goes out of scope, the pointer is deleted. But if we initialize b with the value of a:

b now owns the pointer. Use of the copy constructor or the assignment operator causes a to release ownership of the pointer. Now if a goes out of scope the pointer is not affected. However, the pointer is deleted when b goes out of scope.


NOTE -- The standard container templates cannot be specialized on auto_ptr objects. Copying or assigning from an auto_ptr object transfers ownership of the contained pointer, which changes the source object. Therefore, auto_ptr objects do not meet the Assignable and CopyConstructible requirements of standard containers. See Chapter 4 for container requirements.

The use of new within the constructor for a may seem a little odd. Normally we avoid constructs like this since it puts the responsibility for deletion on a different entity than the one responsible for allocation. In this case, however, the sole responsibility of the auto_ptr is to manage the deletion. This syntax is actually preferable since it prevents us from accidentally deleting the pointer ourselves. or initializing another auto_ptr object with it.

Use operator*(), operator->() or the member function get() to access the pointer held by an auto_ptr. For instance, we can use any of the three following statements to assign "What's up Doc" to the string now pointed to by the auto_ptr b:

Class auto_ptr also provides a release member function that releases ownership of a pointer. Any auto_ptr that does not own a specific pointer is assumed to contain the null pointer, so calling release on an auto_ptr will set the contained pointer to zero. In the example above, when a is copied to b, the pointer held by a is released and set to the null pointer.



Previous fileTop of DocumentContentsIndex pageNext file