smart pointer#Handles

aesthetics  →
being  →
complexity  →
database  →
enterprise  →
ethics  →
fiction  →
history  →
internet  →
knowledge  →
language  →
licensing  →
linux  →
logic  →
method  →
news  →
perception  →
philosophy  →
policy  →
purpose  →
religion  →
science  →
sociology  →
software  →
truth  →
unix  →
wiki  →
essay  →
feed  →
help  →
system  →
wiki  →
critical  →
discussion  →
forked  →
imported  →
original  →
smart pointer#Handles
[ temporary import ]
please note:
- the content below is remote from Wikipedia
- it has been imported raw for GetWiki
{{refimprove|date=June 2015}}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.WEB,weblink[16.20], C++ FAQs Lite's sections on reference-counted smart pointers and copy-on-write reference semantics in the freestore management FAQs, Kline,Marshall, September 1997,, 6 April 2018, WEB,weblink proposal to standardize counted_ptr in the C++ standard library, Colvin,Gregory, 1994,, 6 April 2018, 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.Several types of smart pointers exist. Some work with reference counting, others by assigning ownership of an object to one pointer. If a language supports automatic garbage collection (for example, Java or C#), then smart pointers are unneeded for the 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.


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.WEB,weblink Stroustrup, Bjarne, A history of C++: 1979–1991, 6 April 2018, Simula67's ancestor was Simula I. Insofar as Simula I's element is analogous to C++'s pointer without null, and insofar as Simula I's process with a dummy-statement as its activity body is analogous to C++'s struct (which itself is analogous to C.A.R. Hoare's record in then-contemporary 1960s work), Simula I had reference counted elements (i.e., pointer-expressions that house indirection) to processes (i.e., records) no later than September 1965, as shown in the quoted paragraphs below.WEB,weblink Dahl, Ole-Johan and Nygaard, Kristen, SIMULA—An ALGOL-based simulation language, September 1966,, 6 April 2018, Processes can be referenced individually. Physically, a process reference is a pointer to an area of memory containing the data local to the process and some additional information defining its current state of execution. However, for reasons stated in the Section 2.2 process references are always indirect, through items called elements. Formally a reference to a process is the value of an expression of type element.…element values can be stored and retrieved by assignments and references to element variables and by other means.The language contains a mechanism for making the attributes of a process accessible from the outside, i.e., from within other processes. This is called remote access- ing. A process is thus a referenceable data structure.It is worth noticing the similarity between a process whose activity body is a dummy statement, and the record concept recently proposed by C. A. R. Hoare and N. WirthBecause C++ borrowed Simula's approach to memory allocation{{Em dash}}the new keyword when allocating a process/record to obtain a fresh element to that process/record{{Em dash}}it is not surprising that C++ eventually resurrected Simula's reference-counted smart-pointer mechanism within element as well.


In C++, a smart pointer is implemented as a template class that mimics, by means of operator overloading, the behaviors of a traditional (raw) pointer, (e.g. dereferencing, assignment) while providing additional memory management features.Smart pointers can facilitate intentional programming by expressing, in the type, how the memory of the referent of the pointer will be managed. For example, if a C++ function returns a pointer, there is no way to know whether the caller should delete the memory of the referent when the caller is finished with the information.some_type* ambiguous_function(); // What should be done with the result?Traditionally, naming conventions have been used to resolve the ambiguity,WEB,weblink Taligent's Guide to Designing Programs, section Use special names for copy, create, and adopt routines, 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 unique_ptr,std::unique_ptr obvious_function();The declaration of the function return type as a unique_ptr makes explicit the fact that the caller takes ownership of the result, and the C++ runtime ensures that the memory for *some_type will be reclaimed automatically. Before C++11, unique_ptr can be replaced with auto_ptr.

Creating new objects

To ease the allocation of a std::shared_ptrC++11 introduced:
auto s = std::make_shared(constructor, parameters, here);
and similarly std::unique_ptrSince C++14 one can use:
auto u = std::make_unique(constructor, parameters, here);
It is preferred, in almost all circumstances, to use these facilities over the new keyword:WEB, Sutter, Herb, Herb Sutter, Trip Report: ISO C++ Spring 2013 Meeting,weblink 20 April 2013,, 14 June 2013,


C++11 introduces {{code|std::unique_ptr}}, defined in the header {{code|}}.ISO 14882:2011 20.7.1A {{code|unique_ptr}} is a container for a raw pointer, which the unique_ptr is said to own. A unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment), but the {{code|std::move}} function can be used to transfer ownership of the contained pointer to another {{code|unique_ptr}}. A unique_ptr cannot be copied because its copy constructor and assignment operators are explicitly deleted.std::unique_ptr p1(new int(5));std::unique_ptr p2 = p1; //Compile error.std::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 {{code|auto_ptr}} do not actually copy the stored pointer. Instead, they transfer it, leaving the prior {{code|auto_ptr}} object empty. This was one way to implement strict ownership, so that only one {{code|auto_ptr}} object can own the pointer at any given time. This means that {{code|auto_ptr}} should not be used where copy semantics are needed.CERT C++ Secure Coding Standard{{cn|date=September 2016}} Since {{code|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.

shared_ptr and weak_ptr

C++11 introduces {{code|std::shared_ptr}} and {{code|std::weak_ptr}}, defined in the header {{code|}}. C++11 also introduces {{Code|std::make_shared}} ({{Code|std::make_unique}} was introduced in C++14) to safely allocate dynamic memory in the RAII paradigm.ISO 14882:2014 20.7.1A {{code|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 {{code|shared_ptr}}. An object referenced by the contained raw pointer will be destroyed when and only when all copies of the {{code|shared_ptr}} have been destroyed.std::shared_ptr p0(new int(5)); // valid, allocates 1 integer and initialize it with value 5std::shared_ptr p1(new int[5]); // valid, allocates 5 integersstd::shared_ptr p2 = p1; //Both now own the memory.p1.reset(); //Memory still exists, due to p2.p2.reset(); //Deletes the memory, since no one else owns the memory.A {{code|weak_ptr}} is a container for a raw pointer. It is created as a copy of a shared_ptr. The existence or destruction of {{code|weak_ptr}} copies of a shared_ptr have no effect on the shared_ptr or its other copies. After all copies of a shared_ptr have been destroyed, all weak_ptr copies become empty.std::shared_ptr p1 = std::make_shared(5);std::weak_ptr wp1 {p1}; //p1 owns the memory.{
std::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) {
}//p2 is destroyed. Memory is owned by p1.p1.reset(); // Delete the memory.std::shared_ptr p3 = wp1.lock(); //Memory is gone, so we get an empty shared_ptr.if (p3) { // code will not execute
}Because the implementation of {{code|shared_ptr}} uses reference counting, circular references are potentially a problem. A circular shared_ptr chain can be broken by changing the code so that one of the references is a weak_ptr.Multiple threads can safely simultaneously access different {{code|shared_ptr}} and {{code|weak_ptr}} objects that point to the same object.boost::shared_ptr thread safety (does not formally cover std::shared_ptr, but is believed to have the same threading limitations)The referenced object must be protected separately to ensure thread safety.{{code|shared_ptr}} and {{code|weak_ptr}} are based on versions used by the Boost libraries.{{citation needed|date = January 2014}} 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.

See also



Further reading

External links

- content above as imported from Wikipedia
- "smart pointer#Handles" does not exist on GetWiki (yet)
- time: 3:19am EST - Fri, Feb 22 2019
[ this remote article is provided by Wikipedia ]
LATEST EDITS [ see all ]
M.R.M. Parrott