A smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic memory management or bounds checking. These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency. Smart pointers typically keep track of the memory they point to. They may also be used to manage other resources, such as network connections and file handles.
Smart pointers prevent most situations of memory leaks by making the memory deallocation automatic.More generally, they make object destruction automatic: the object controlled by a smart pointer is automatically destroyed (finalized and then deallocated) when the last (or only) owner of the object is destroyed.
Smart pointers also eliminate dangling pointers by postponing destruction until the object is no longer in use.
Several types of smart pointers exist. Some work with reference counting, others by assigning ownership of the object to a single pointer. If the language supports automatic garbage collection (for instance, Java or C#), then smart pointers are unnecessary for memory management, but may still be useful in resource management of other resources, such as file handles or network sockets
Smart pointers can facilitate intentional programming by expressing the use of a pointer in the type itself. For example, if a C++ function returns a pointer, there is no way to know whether the caller should delete the memory pointed to when the caller is finished with the information.
some_type* ambiguous_function(); // What should be done with the result?
Traditionally, this has been solved with comments, but this can be error-prone. The potential problems associated with this use can be mitigated by instead returning a unique_ptr
,
unique_ptr<some_type> obvious_function1();
The function makes explicit that the caller will take ownership of the result. Furthermore, no memory will be leaked if the caller does nothing. Prior to C++11, unique_ptr can be replaced with auto_ptr.