In computer science, a smart pointer is an abstract data type that simulates a pointer while providing added features, such as automatic memory management or bounds checking. Such 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, and may also be used to manage other resources, such as network connections and file handles. Smart pointers were first popularized in the programming language C++ during the first half of the 1990s as rebuttal to criticisms of C++'s lack of automatic garbage collection. In previous versions of Rust, there was also a that wrapped around raw non-null .
It is possible to use "smart void pointers" using <code>std::unique_ptr</code>, using its second template parameter <code>Deleter</code>, which stores a type of a deallocator.
<syntaxhighlight lang="cpp">
using std::unique_ptr;
struct MyDeleter {
void operator()(void* p) const {
delete static_cast<int*>(p);
}
};
int main() {
unique_ptr<void, MyDeleter> myPointer(new int(42), MyDeleter());
}
</syntaxhighlight>
Shared pointers and weak pointers
C++11 introduces and , defined in the header .
Hazard pointers
Starting in C++26, there is a new pointer defined in , the hazard pointer (). It is a single-writer multi-reader pointer that can be owned by at most one thread at any point in time.
The hazard pointer had existed already previously in some third-party libraries.
Other types of smart pointers
There are other types of smart pointers (which are not in the C++ standard) implemented on popular C++ libraries or custom STL, some examples include the intrusive pointer.
See also
- auto_ptr
- Fat pointer
- Tagged pointer
- Opaque pointer
- Reference (computer science)
- Boost (C++ libraries)
- Automatic Reference Counting
- Resource acquisition is initialization (RAII)
- Garbage collection in computer programming
References
Further reading
- Smart Pointers - What, Why, Which?. Yonat Sharon
- Smart Pointers Overview. John M. Dlugosz
External links
- countptr.hpp. The C++ Standard Library - A Tutorial and Reference by Nicolai M. Josuttis
- Boost Smart Pointers
- Smart Pointers in Delphi
- Smart Pointers in Rust
- Smart Pointers in Modern C++
