Boost logo

Boost :

From: Darin Adler (darin_at_[hidden])
Date: 1999-12-04 13:26:25


After Greg Colvin posted his implementation of weak pointers and garbage
collection, I started thinking about why I use smart pointers in my
programs, and what interface would be most useful for me. The following is
either a proposal or a wish list.

My motivation for using smart pointers is to delete the referenced object
when it's no longer in use, and to avoid two pitfalls of normal pointers:

    1) invalid pointers after an object has been deleted
    2) null pointers

The two pitfalls above come into play any time you use the * or -> operator.
Every time you use * or -> you must have some guarantee that the pointer
still points to an object. I like smart pointers because they guarantee that
* or -> is legal. Because of these goals, I'd like these kinds of smart
pointers:

    1) strong pointer -- The holder of this pointer owns the object and
knows it won't be deleted. This type can not hold a null pointer.
    2) weak pointer -- The holder of this pointer knows the object won't be
deleted, because it has some higher-level knowledge about the object
lifetime. For example "this object is owned by another object, which will
delete me first" or something like that. If the underlying object is deleted
while there's an outstanding weak pointer, an exception is raised.

Neither of these would ever be null. To handle the kind of pointer that can
be null, I'd have two other types.

    3) optional strong pointer -- This can hold a strong pointer or null. It
uses an interface that promotes checking for null.
    4) optional weak pointer -- This can hold a weak pointer or null. Unlike
a weak pointer, if the underlying object is deleted, this will just become
null.

The optional strong and optional weak types would have an interface where
you can check if the pointer is null or not (call it good() or empty()?),
clear the pointer (call it clear()?) and get the pointer (call it get()?).
The get() operation would raise an exception if the pointer is null and
would return one of the non-null smart pointer types. There wouldn't be any
* or -> operator for these types, so in a way they are not really smart
pointers, but rather holders for smart pointers.

The auto_ptr, scoped_ptr, shared_ptr, cyclic_ptr, and weak_ptr classes as
they currently exist fall short for me because they all allow null pointers,
which are almost as difficult to deal with as invalid pointers are.

Thoughts?

    -- Darin


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk