A class utilizing the C++ features of destructors and operator overloading in order to provide pointer objects which imitate plain old C/C++ pointers but which automatically free the dynamic allocation memory of the objects they reference upon destruction.

Implemented as auto_ptr in the C++ STL.

(C++ programming; other computer languages can't provide such and/or don't need them)

A smart pointer is any class that provides "pointer-like" semantics. Typically a smart pointer to a type T will implement the following:

T& operator*() const (or const T& operator*() const, for a "smart const pointer")
This permits access to the pointed-at T. Sometimes the return type will not be a T&, but instead a T or even a proxy class for T.
A operator->() method
This permits direct access to elements of T. Note that the special semantics of operator-> mean it need not return a T* -- it might be anything that supports another operator-> method.
Smart pointers are often used for memory management, in which case you may well find special behaviour in their destructor and constructor methods. Other methods may well be added; the operator++ methods and the operator-- methods are common.

Other uses for smart pointers include:

Locking object access
Access to the pointed-at object can be protected by a lock; writes and reads can be differentiated by returning different types based on const-ness.
Wrappers for objects located on external (random access) storage
The object is fetched to perform actions on it, but need not remain resident in memory.
Marking pointer ownership
This is what the STL auto_ptr really does: the offered memory management is trivial-to-useless, but marking a parameter auto_ptr clearly says ownership of the pointed-at object is being transferred.
Iterators
An iterator is really just a smart pointer!

Generic smart pointers (such as auto_ptr) are templates. More specific smart pointers are often implemented directly, without using templates, instead using specific properties of the pointed-at object.

The only standard smart pointer is auto_ptr, which is limited. An upcoming version of the standard should include better standard smart pointers. The Boost library has several types of smart pointers (which will probably end up being standardized; they're there in the drafts for std::tr1). Andrei Alexandrescu's Loki library has a fairly unique generic generic smart pointer: by passing different policy classes into the smart pointer template, you can get very different smart pointers.

Log in or registerto write something here or to contact authors.