FazBrowse Wikipedia Viewer | Main Page |
Search Wikipedia:
|
Viewing: https://en.wikipedia.org/wiki/Smart_pointer#Unique_pointers

Smart pointer

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

History

edit

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>()).

filePtr(std::fopen(\"data.txt\", \"r\"), &std::fclose);\n"}}'>usingstd::FILE; usingstd::unique_ptr; unique_ptr<FILE,decltype(&std::fclose)>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<T>() and std::make_shared<T>() can only call public constructors.

create(int n) {\n return unique_ptr<X>(new X(n));\n }\n};\n"}}'>usingstd::unique_ptr; classX{ private: intn; X()=default; public: staticunique_ptr<X>create(intn){ returnunique_ptr<X>(newX(n)); } };

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.

data;\n size_t rows;\n size_t cols;\n};\n\nunique_ptr<Matrix> m(new Matrix {\n .data = {\n 1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 0.0, 1.0\n },\n .rows = 3,\n .cols = 3\n});\n"}}'>usingstd::unique_ptr; usingstd::vector; structMatrix{ vector<double>data; size_trows; size_tcols; }; unique_ptr<Matrix>m(newMatrix{ .data={ 1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0 }, .rows=3, .cols=3 });

Unique pointers

edit

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>).

(p);\n }\n};\n\nint main() {\n unique_ptr<void, MyDeleter> myPointer(new int(42), MyDeleter());\n}\n"}}'>usingstd::unique_ptr; structMyDeleter{ voidoperator()(void*p)const{ deletestatic_cast<int*>(p); } }; intmain(){ unique_ptr<void,MyDeleter>myPointer(newint(42),MyDeleter()); }

Shared pointers and weak pointers

edit

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().

Other types of smart pointers

edit

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

edit

References

edit
{{cite web |url=http://www.cis.usouthal.edu/faculty/drh/c%2B%2Bfaq/freestore-mgmt.html#[16.20 |title=C++ FAQs Lite's sections on reference-counted smart pointers and copy-on-write reference semantics in the freestore management FAQs |author-last=Kline |author-first=Marshall |date=September 1997 |website=cis.usouthal.edu |access-date=2018-04-06}}</ref>\n<ref name=\"Colvin_1994\">{{cite web |url=http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1994/N0555.pdf |title=proposal to standardize counted_ptr in the C++ standard library |author-last=Colvin |author-first=Gregory |date=1994 |website=open-std.org |access-date=2018-04-06}}</ref>\n<ref name=\"Stroustrup\">{{cite web |url=http://www.stroustrup.com/hopl2.pdf |author-last=Stroustrup |author-first=Bjarne |title=A history of C++: 1979–1991 |access-date=2018-04-06}}</ref>\n<ref name=\"Dahl-Nygaard_1966\">{{cite web |url=http://folk.uio.no/simula67/Archive/artikkel1966cacm.pdf |author-last1=Dahl |author-first1=Ole-Johan |author-last2=Nygaard |author-first2=Kristen |title=SIMULA—An ALGOL-based simulation language |date=September 1966 |website=folk.uio.no |access-date=2018-04-06}}</ref>\n<ref name=\"Taligent\">{{cite web |url=https://root.cern.ch/TaligentDocs/TaligentOnline/DocumentRoot/1.0/Docs/books/WM/WM_67.html#HEADING81 |title=Taligent's Guide to Designing Programs, section Use special names for copy, create, and adopt routines}}</ref>\n<ref name=\"Sutter_2013\">{{cite web |author-last=Sutter |author-first=Herb |author-link=Herb Sutter |title=Trip Report: ISO C++ Spring 2013 Meeting |url=http://isocpp.org/blog/2013/04/trip-report-iso-c-spring-2013-meeting |date=2013-04-20 |website=isocpp.org |access-date=2013-06-14}}</ref>\n<ref name=\"ISO14882_2011\">ISO&nbsp;14882:2011 20.7.1</ref>\n<ref name=\"CERT\">CERT C++ Secure Coding Standard</ref>\n<ref name=\"ISO14882_2014\">ISO&nbsp;14882:2014 20.7.1</ref>\n<ref name=\"Boost\">{{cite web |url=http://www.boost.org/libs/smart_ptr/shared_ptr.htm#ThreadSafety |title=boost::shared_ptr thread safety}} (NB. Does not formally cover std::shared_ptr, but is believed to have the same threading limitations.)</ref>\n<ref name=\"Klabnik-Nichols_2023\">{{cite book |title=The Rust Programming Language |chapter=15. Smart Pointers |date=2023 |orig-date=2018<!-- 1st edition --> |edition=2 |author-first1=Steve |author-last1=Klabnik |author-first2=Carol |author-last2=Nichols |publisher=[[No Starch Press, Inc.]] |publication-place=San Francisco, California, USA |isbn=978-1-7185-0310-6 <!-- |lccn=1st edition: 2018014097 --> |pages=315–351 }} (xxix+1+527+3 pages)</ref>"}},"i":0}}]}'>
Colvin, Gregory (1994). "proposal to standardize counted_ptr in the C++ standard library" (PDF). open-std.org. Retrieved 2018-04-06.
  • ↑ Dahl, Ole-Johan; Nygaard, Kristen (September 1966). "SIMULA—An ALGOL-based simulation language" (PDF). folk.uio.no. Retrieved 2018-04-06.
  • ↑ cppreference.com. "std::auto_ptr". cppreference.com. cppreference.com. Retrieved 2026-07-11.
  • ↑ cppreference.com. "std::weak_ptr". cppreference.com. cppreference.com. Retrieved 2026-07-11.
  • ↑ "},"url":{"wt":"https://en.cppreference.com/cpp/header/hazard_pointer"},"website":{"wt":"cppreference.com"},"publisher":{"wt":"cppreference.com"},"access-date":{"wt":"11 July 2026"},"author":{"wt":"cppreference.com"}},"i":0}}]}'/>cppreference.com. "Standard library header <hazard_pointer>". cppreference.com. cppreference.com. Retrieved 2026-07-11.
  • ↑ "Box in std::boxed". doc.rust-lang.org. 2025-08-04.
  • ↑ "Weak in std::rc". doc.rust-lang.org. 2025-08-04.
  • ↑ Meyers, Scott (2014). Effective Modern C++. Sebastopol, California, USA: O'Reilly Media. ISBN 978-1-49190399-5. OCLC 884480640.

  • View original on Wikipedia | Back | FazBrowse Home