Smart pointer

A smart pointer is any class which provides automatic management of the lifetime of a dynamically allocate object (pointer). It is probably the most common form of RAII.

Typically a smart pointer will provide operator* and operator-> so that it can be used as if it were a pointer. A common implementation of a smart pointer (such as boost::shared_ptr) will provide reference counted copy semantics; copying the object increasing the reference count of the pointer, and destruction of a smart pointer reduces the reference count. When the reference count reaches 0, the pointer is deleted. This kind of smart pointer is used to manage situations with complicated transfer of ownership.

Other smart pointers include the simple std::auto_ptr, the only smart pointer in the 1998 C++ standard. auto_ptr provides automatic releasing of storage when it is destructed, but does not provide reference counting or useful copying semantics. auto_ptr is typically used to manage the lifetime of a pointer within a single function when exception safety is required.

Problems with smart pointers

 * Reference loops: when two objects managed by smart pointers refer to each other, the reference count of each object will never decrease to 0 even when no other objects refer to the pointers. This is a form of memory leak.  The two usual methods to solve this are explicit release, when the pointer is instructed to release its pointer and decrement the reference count, and "weak pointers".  A weak pointer refers to a smart pointer, but does not participate in the reference count; when the reference count is 0, the weak pointer becomes invalid and cannot be dereferenced anymore.