Top of document
©Copyright 1999 Rogue Wave Software

Declaration and Initialization of Auto Pointers

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 auto_ptr's copy constructor or assignment operator transfers ownership from one auto_ptr object to another. For instance, suppose we create auto_ptr a like this:

auto_ptr<string> a(new string);
 

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 will be deleted. But, if we assign a to b, using the assignment operator:

auto_ptr<string> b = a;
 

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

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. But in this case, the auto_ptr's sole responsibility is to manage the deletion. This syntax is actually preferable since it prevents us from accidentally deleting the pointer ourselves.

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.

*b = "What's up Doc";
 *(b.get()) = "What's up Doc";
  b->assign("What's up Doc");
 

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 point to the NULL pointer, so calling release on an auto_ptr will set it to the NULL pointer. In the example above, when a is assigned to b, the pointer held by a is released and a is set to the NULL pointer.


Top of document