A pointer is a variable containing the address of some other object in memory. The pointer variable can be allocated:
- on the stack (as a local
auto
variable in a function or statement block)
- statically (as a global variable or static class member)
- on the heap (as a
new
object or as a class object member)
The object that the pointer points to (references) can likewise be allocated in these three places as well. Generally speaking, though, a pointed-to object is allocated using the new
operator.
Local variables go out of scope when the program flow leaves the block (or function) that they are declared within, i.e., their presence on the stack disappears. Similarly, member variables of an object disappear when their parent object goes out of scope or is deleted from the heap.
If a pointer goes out of scope or its parent object is deleted, the object that the pointer references still exists in memory. Thus the rule of thumb that any code that allocates (news
) an object owns the object and should also delete
that object when it's no longer needed.
Auto-pointers take some of the drudgery out of the management of the pointed-to object. An object that has been allocated through an auto_ptr
is deleted when that pointer goes out of scope. The object can be assigned from its owning auto_ptr
to another auto_ptr
, which transfers object ownership to the second pointer.
References are essentially pointers in disguise, but that's a topic for another discussion.