Smart pointers

The standard library and Boost smart pointers fall into two types: scoped pointers and reference counted pointers.

Scoped pointers

boost::scoped_ptr and std::unique_ptr
The object is destroyed when the pointer instance goes out of scope.
They cannot be copied (although you can pass them by reference)
The lifetime of the object is tied either to:

  • The current scope
  • The lifetime of the containing object

The second of these makes them suitable for storage in containers.
The old std::auto_ptr is like a scoped pointer, except that it can be copied, which transfers ownership.
It is deprecated in the newer standards and should not be used.

Reference counted pointers

boost::shared_ptr and std::shared_ptr
Allows the pointer to be copied.
Useful when the lifetime of the object is more complicated.
Potential problems:

  • Creating them on the heap
  • Passing them by reference
  • Creating circular references

The last point is mitigated by boost::weak_ptr and std::weak_ptr, which define a weak (i.e., uncounted) reference to a shared_ptr.