---
title: Smart pointer
slug: smart-pointer
qid: 
snapshot: enwiki-001373734993
content_hash: 
license: CC BY-SA 4.0
source: https://en.wikipedia.org/w/index.php?oldid=1373734993
tags: [109374363, 20282650, 22905584, 22933719, 22936462, 22938513, 23000002, 23118434, 23603337, 24043274, 24745122, 27395026]
---

# Smart pointer

> [!note] Provenance
> Snapshot `enwiki-001373734993` · content root `…`
> Derived from <https://en.wikipedia.org/w/index.php?oldid=1373734993> · Licensed CC BY-SA 4.0

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 during the first half of the 1990s as rebuttal to criticisms of lack of automatic garbage collection. Rust, which avoids raw pointers and uses ownership to dictate lifetimes, also has smart pointers. Pointer misuse can be a major source of bugs. Smart pointers prevent most situations of memory leaks by making the memory deallocation automatic. More generally, they make object destruction automatic: an object controlled by a smart pointer is automatically destroyed (finalized and then deallocated) when the last (or only) owner of an object is destroyed, for example because the owner is a local variable, and execution leaves the variable's scope. Smart pointers also eliminate dangling pointers by postponing destruction until an object is no longer in use.…

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 during the first half of the 1990s as rebuttal to criticisms of lack of automatic garbage collection. Rust, which avoids raw pointers and uses ownership to dictate lifetimes, also has smart pointers. Pointer misuse can be a major source of bugs. Smart pointers prevent most situations of memory leaks by making the memory deallocation automatic. More generally, they make object destruction automatic: an object controlled by a smart pointer is automatically destroyed (finalized and then deallocated) when the last (or only) owner of an object is destroyed, for example because the owner is a local variable, and execution leaves the variable's scope. Smart pointers also eliminate dangling pointers by postponing destruction until an object is no longer in use. If a language supports automatic garbage collection (for example, Java or C#), then smart pointers are unneeded for reclaiming and safety aspects of memory management, yet are useful for other purposes, such as cache data structure residence management and resource management of objects such as file handles or network sockets. Java, although not having a pointer API, has similar concepts for dealing with references. Several types of smart pointers exist. Some work with reference counting, others by assigning ownership of an object to one pointer. X* ambiguousFunction(); // What should be done with the result? Traditionally, naming conventions have been used to resolve the ambiguity, which is an error-prone, labor-intensive approach. C++11 introduced a way to ensure correct memory management in this case by declaring the function to return a std::unique_ptr , using std::unique_ptr; unique_ptr obviousFunction(); The declaration of the function return type as a std::unique_ptr makes explicit the fact that the caller takes ownership of the result, and the C++ runtime ensures that the memory will be reclaimed automatically. Before C++11's introduction of std::unique_ptr , the std::auto_ptr class was used (eventually removed in C++17). C++ offers the following smart pointers: std::auto_ptr (deprecated in C++11 and removed in C++17) , an "auto pointer" std::unique_ptr , a "unique pointer" std::shared_ptr , a "shared pointer" std::weak_ptr , a "weak pointer" In C++26, a new pointer was added, defined in : the hazard pointer ( ). However, despite its name, it is not a smart pointer, but rather a concurrency tool. It is a single-writer multi-reader pointer that can be owned by at most one thread at any point in time. For an object to be hazard-protectable, it must inherit from std::hazard_pointer_obj_base . The hazard pointer had existed already previously in some third-party libraries. using std::shared_ptr; shared_ptr s = std::make_shared (/* constructor parameters here */); Similarly for std::unique_ptr , C++14 introduced the std::make_unique () factory function: using std::unique_ptr; unique_ptr u = std::make_unique (/* constructor parameters here */); It is preferred, in almost all circumstances, to use these factory functions over the new keyword , however, this is not always possible. One must manually invoke the std::unique_ptr constructor to add custom deletion logic, as std::unique_ptr cannot set the Del template parameter (which stores the custom deleter type) through std::make_unique () ). using std::FILE; using std::unique_ptr; unique_ptr filePtr(std::fopen("data.txt", "r"), &std::fclose); Furthermore, to call private/protected constructors, one must create the smart pointer manually, as std::make_unique () and std::make_shared () can only call public constructors. using std::unique_ptr; class X { private: int n; X() = default; public: static unique_ptr create(int n) { return unique_ptr (new X(n)); } }; In addition, std::make_unique () and std::make_shared () forward parameters via parentheses rather than braces; thus, one can only construct aggregates and std::initializer_list constructors through manually creating a smart pointer. using std::unique_ptr; using std::vector; struct Matrix { vector data; size_t rows; size_t cols; }; unique_ptr m(new Matrix { .data = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }, .rows = 3, .cols = 3 }); import std; using std::unique_ptr; unique_ptr p1(new int(5)); unique_ptr p2 = p1; // Compile error. unique_ptr p3 = std::move(p1); // Transfers ownership. p3 now owns the memory and p1 is set to nullptr. p3.reset(); // Deletes the memory. p1.reset(); // Does nothing. std::auto_ptr is deprecated under C++11 and completely removed from C++17. The copy constructor and assignment operators of do not actually copy the stored pointer. Instead, they transfer it, leaving the prior object empty. This was one way to implement strict ownership, so that only one object can own the pointer at any given time. This means that should not be used where copy semantics are needed. Since already existed with its copy semantics, it could not be upgraded to be a move-only pointer without breaking backward compatibility with existing code. The Rust equivalent of unique pointers is , which has unique ownership of a heap allocated object. In previous versions of Rust, there was also a that wrapped around raw non-null . It is possible to use "smart void pointers" using std::unique_ptr , using its second template parameter Del , which stores a type of a deallocator (by default std::default_delete ). using std::unique_ptr; struct MyDeleter { void operator()(void* p) const { delete static_cast (p); } }; int main() { unique_ptr myPointer(new int(42), MyDeleter()); } import std; using std::shared_ptr; shared_ptr p0(new int(5)); // Valid, allocates 1 integer and initialize it with value 5. shared_ptr p1(new int[5]); // Valid, allocates 5 integers. shared_ptr p2 = p1; // Both now own the memory. p1.reset(); // Memory still exists, due to p2. p2.reset(); // Frees the memory, since no one else owns the memory. A is a container for a raw pointer. It is created as a copy of a shared_ptr . The existence or destruction of copies of a std::shared_ptr have no effect on the std::shared_ptr or its other copies. After all copies of a std::shared_ptr have been destroyed, all std::weak_ptr copies become empty. import std; using std::shared_ptr; using std::weak_ptr; shared_ptr p1 = std::make_shared (5); weak_ptr wp1{p1}; // p1 owns the memory. { shared_ptr p2 = wp1.lock(); // Now p1 and p2 own the memory. // p2 is initialized from a weak pointer, so you have to check if the // memory still exists! if (p2) { useSomePointer(p2); } } // p2 is destroyed. Memory is owned by p1. p1.reset(); // Free the memory. shared_ptr p3 = wp1.lock(); // Memory is gone, so we get an empty shared_ptr. if (p3) { // code will not execute useLivePointer(p3); } Because the implementation of uses reference counting, circular references are potentially a problem. A circular std::shared_ptr chain can be broken by changing the code so that one of the references is a std::weak_ptr . Multiple threads can safely simultaneously access different and objects that point to the same object. The referenced object must be protected separately to ensure thread safety. and are based on versions used by the Boost libraries. C++ Technical Report 1 (TR1) first introduced them to the standard, as general utilities, but C++11 adds more functions, in line with the Boost version. In Java, every object is effectively a shared reference, and the Java Virtual Machine (JVM) tracks object reachability. Rust has two kinds of shared pointers, (reference-counted, single-threaded) and (atomically reference-counted, thread-safe). Java has an equivalent concept to weak pointers, (implementing a weak reference), which does not increase the reference count of an object, and can check that an object still lives using get() . Java similarly has the (implementing a phantom reference), used with a , for performing cleanup actions after an object is garbage collected, but prior to finalisation. Unlike ), cannot actually access the object. , on the other hand, are cleared according to the discretion of the garbage collector. Rust has a for a weak, non-owning reference which is created from an or by using .
