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:
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 is 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 is not affected. However, the pointer is 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. 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.
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");
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 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.
OEM Edition, OEM Edition, ©Copyright 1999, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.