| FazBrowse Wikipedia Viewer | Main Page | | |
| Viewing: https://en.wikipedia.org/wiki/Smart_pointer#Unique_pointers |
| Contents |
|---|
| History |
| Unique pointers |
| Shared pointers and weak pointers |
| Other types of smart pointers |
| See also |
| References |
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
Even though C++ popularized the concept of smart pointers, especially the reference-counted variety, the immediate predecessor of one of the languages that inspired C++'s design had reference-counted references built into the language. C++ was inspired in part by Simula67. Simula67's ancestor was Simula I. Insofar as Simula I's element is analogous to C++'s pointer without new keyword when allocating a process/record to obtain a fresh element to that process/recordusingstd::unique_ptr; unique_ptr<X>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:
In C++26, a new pointer was added, defined in "},"parts":[{"template":{"target":{"wt":"code","href":"./Template:Code"},"params":{"1":{"wt":"<hazard_pointer>"}},"i":0}}]}'><hazard_pointer>: the hazard pointer (usingstd::unique_ptr; unique_ptr<X>u=std::make_unique<X>(/* 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<T, Del> constructor to add custom deletion logic, as std::unique_ptr<T, Del> cannot set the Del template parameter (which stores the custom deleter type) through std::make_unique<T>()).
Furthermore, to call private/protected constructors, one must create the smart pointer manually, as std::make_unique<T>() and std::make_shared<T>() can only call public constructors.
In addition, std::make_unique<T>() and std::make_shared<T>() forward parameters via parentheses rather than braces; thus, one can only construct aggregates and std::initializer_list<T> constructors through manually creating a smart pointer.
C++11 introduces std::unique_ptr is a container for a raw pointer, which the std::unique_ptr is said to own. A std::unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment), but the importstd; usingstd::unique_ptr; unique_ptr<int>p1(newint(5)); unique_ptr<int>p2=p1;// Compile error. unique_ptr<int>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 std::auto_ptr object can own the pointer at any given time. This means that std::auto_ptr 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 *mut T.
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<T>).
C++11 introduces <memory>. C++11 also introduces std::shared_ptr is a container for a raw pointer. It maintains reference counting ownership of its contained pointer in cooperation with all copies of the importstd; usingstd::shared_ptr; shared_ptr<int>p0(newint(5));// Valid, allocates 1 integer and initialize it with value 5. shared_ptr<int[]>p1(newint[5]);// Valid, allocates 5 integers. shared_ptr<int[]>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 importstd; usingstd::shared_ptr; usingstd::weak_ptr; shared_ptr<int>p1=std::make_shared<int>(5); weak_ptr<int>wp1{p1};// p1 owns the memory. { shared_ptr<int>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<int>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 std::weak_ptr objects that point to the same object.
The referenced object must be protected separately to ensure thread safety.
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, java.lang.ref.WeakReference (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 java.lang.ref.WeakReference), std::rc::Weak for a weak, non-owning reference which is created from an downgrade().
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.
| View original on Wikipedia | Back | FazBrowse Home |