Smart Pointers

The solution to this dilemma is to create an

auto_ptr
. An
auto_ptr
is a stack-based object, which encapsulates a pointer and which is destroyed when the stack is unwound. This is critical: memory on the heap is managed by an
auto_ptr
on the stack. When an exception is thrown, the stack is unwound and the
auto_ptr
is destroyed. As part of its destructor, it deletes the memory on the heap. We thereby ensure that when the exception is thrown, we do not create a memory leak.

The C++ standard library provides an implementation of

auto_ptr
. The
auto_ptr
supplied by the C++ standard library supports the idiom of "resource acquisition is initialization". That is, when you create the
auto_ptr
, you allocate the memory, and when you destroy the
auto_ptr
, the memory is returned. Once the
auto_ptr
is created, you can use it like a pointer, but it will ensure that the memory will be de-allocated when it is destroyed.

It is important to note that an

auto_ptr
owns the object to which it points. Copying
auto_ptr
s has a special set of semantics: when you copy one
auto_ptr
to another, you transfer this ownership. This is to prevent having that object deleted more than once.

© 1998 by Wrox Press. All rights reserved.