Smart pointer
   HOME

TheInfoList



OR:

In
computer science Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, a smart pointer is an
abstract data type In computer science, an abstract data type (ADT) is a mathematical model for data types. An abstract data type is defined by its behavior (semantics) from the point of view of a ''user'', of the data, specifically in terms of possible values, pos ...
that simulates a pointer while providing added features, such as automatic
memory management Memory management is a form of resource management applied to computer memory. The essential requirement of memory management is to provide ways to dynamically allocate portions of memory to programs at their request, and free it for reuse when ...
or
bounds checking In computer programming, bounds checking is any method of detecting whether a variable is within some bounds before it is used. It is usually used to ensure that a number fits into a given type (range checking), or that a variable being used as ...
. 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++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
during the first half of the 1990s as rebuttal to criticisms of C++'s lack of automatic garbage collection. Pointer misuse can be a major source of bugs. Smart pointers prevent most situations of
memory leak In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released. A memory leak may also happen when an object ...
s 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 Scope or scopes may refer to: People with the surname * Jamie Scope (born 1986), English footballer * John T. Scopes (1900–1970), central figure in the Scopes Trial regarding the teaching of evolution Arts, media, and entertainment * Cinema ...
. 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 Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
or C#), then smart pointers are unneeded for reclaiming and safety aspects of memory management, yet are useful for other purposes, such as
cache Cache, caching, or caché may refer to: Places United States * Cache, Idaho, an unincorporated community * Cache, Illinois, an unincorporated community * Cache, Oklahoma, a city in Comanche County * Cache, Utah, Cache County, Utah * Cache County ...
data structure residence management and
resource management In organizational studies, resource management is the efficient and effective development of an organization's resources when they are needed. Such resources may include the financial resources, inventory, human skills, production resources, or ...
of objects such as
file handle In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier ( handle) for a file or other input/output resource, such as a pipe or network socket. File descriptors typically hav ...
s or
network socket A network socket is a software structure within a network node of a computer network that serves as an endpoint for sending and receiving data across the network. The structure and properties of a socket are defined by an application programmin ...
s. Several types of smart pointers exist. Some work with
reference counting In computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, refer ...
, others by assigning ownership of an object to one pointer.


History

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 Simula is the name of two simulation programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard. Syntactically, it is an approximate superset of AL ...
. Simula67's ancestor was
Simula I Simula is the name of two Simulation language, simulation programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard. Syntax (programming languages), Syn ...
. 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 Sir Charles Antony Richard Hoare (Tony Hoare or C. A. R. Hoare) (born 11 January 1934) is a British computer scientist who has made foundational contributions to programming languages, algorithms, operating systems, formal verification, and c ...
'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.
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. Wirth
Because C++ borrowed
Simula Simula is the name of two simulation programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard. Syntactically, it is an approximate superset of ALGO ...
's approach to memory allocationthe ''new'' keyword when allocating a process/record to obtain a fresh ''element'' to that process/recordit is not surprising that C++ eventually resurrected Simula's reference-counted smart-pointer mechanism within ''element'' as well.


Features

In
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, a smart pointer is implemented as a template class that mimics, by means of
operator overloading In computer programming, operator overloading, sometimes termed ''operator ad hoc polymorphism'', is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading i ...
, the behaviors of a traditional (raw) pointer, (e.g. dereferencing, assignment) while providing additional memory management features. Smart pointers can facilitate
intentional programming In computer programming, Intentional Programming is a programming paradigm developed by Charles Simonyi that encodes in software source code the precise ''intention'' which programmers (or users) have in mind when conceiving their work. By using ...
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. SomeType* 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 C11, C.XI, C-11 or C.11 may refer to: Transport * C-11 Fleetster, a 1920s American light transport aircraft for use of the United States Assistant Secretary of War * Fokker C.XI, a 1935 Dutch reconnaissance seaplane * LET C-11, a license-build ...
introduced a way to ensure correct memory management in this case by declaring the function to return a unique_ptr, std::unique_ptr ObviousFunction(); 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 will be reclaimed automatically. Before
C++11 C11, C.XI, C-11 or C.11 may refer to: Transport * C-11 Fleetster, a 1920s American light transport aircraft for use of the United States Assistant Secretary of War * Fokker C.XI, a 1935 Dutch reconnaissance seaplane * LET C-11, a license-build ...
, unique_ptr can be replaced with
auto_ptr auto_ptr is a class template that was available in previous versions of the C++ standard library (declared in the header file), which provides some basic RAII features for C++ raw pointers. It has been replaced by the unique_ptr class. The au ...
.


Creating new objects

To ease the allocation of a std::shared_ptr
C++11 C11, C.XI, C-11 or C.11 may refer to: Transport * C-11 Fleetster, a 1920s American light transport aircraft for use of the United States Assistant Secretary of War * Fokker C.XI, a 1935 Dutch reconnaissance seaplane * LET C-11, a license-build ...
introduced: auto s = std::make_shared(constructor, parameters, here); and similarly std::unique_ptrSince
C++14 C++14 is a version of the ISO/IEC 14882 standard for the C++ programming language. It is intended to be a small extension over C++11, featuring mainly bug fixes and small improvements, and was replaced by C++17. Its approval was announced on Augus ...
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.


unique_ptr

C++11 C11, C.XI, C-11 or C.11 may refer to: Transport * C-11 Fleetster, a 1920s American light transport aircraft for use of the United States Assistant Secretary of War * Fokker C.XI, a 1935 Dutch reconnaissance seaplane * LET C-11, a license-build ...
introduces , defined in the header . A 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 function can be used to transfer ownership of the contained pointer to another . 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 auto_ptr is a class template that was available in previous versions of the C++ standard library (declared in the header file), which provides some basic RAII features for C++ raw pointers. It has been replaced by the unique_ptr class. The au ...
is
deprecated In several fields, especially computing, deprecation is the discouragement of use of some terminology, feature, design, or practice, typically because it has been superseded or is no longer considered efficient or safe, without completely removing ...
under C++11 and completely removed from
C++17 C17, C-17 or C.17 may refer to: Transportation * , a 1917 British C-class submarine Air * Boeing C-17 Globemaster III, a military transport aircraft * Lockheed Y1C-17 Vega, a six-passenger monoplane * Cierva C.17, a 1928 English experimental ...
. 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 Backward compatibility (sometimes known as backwards compatibility) is a property of an operating system, product, or technology that allows for interoperability with an older legacy system, or with input designed for such a system, especiall ...
with existing code.


shared_ptr and weak_ptr

C++11 introduces and , defined in the header . C++11 also introduces ( was introduced in C++14) to safely allocate dynamic memory in the RAII paradigm. A is a container for a raw pointer. It maintains
reference counting In computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, refer ...
ownership of its contained pointer in cooperation with all copies of the . An object referenced by the contained raw pointer will be destroyed when and only when all copies of the have been destroyed. std::shared_ptr p0(new int(5)); // Valid, allocates 1 integer and initialize it with value 5. std::shared_ptr p1(new int[5]); // Valid, allocates 5 integers. std::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 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 owns the memory. // p2 is destroyed. Memory is owned by p1. p1.reset(); // Free the memory. std::shared_ptr p3 = wp1.lock(); // Memory is gone, so we get an empty shared_ptr. if (p3) Because the implementation of uses
reference counting In computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, refer ...
, 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 and objects that point to the same object. The referenced object must be protected separately to ensure
thread safety Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without un ...
. and are based on versions used by the Boost libraries.
C++ Technical Report 1 C, or c, is the third letter in the Latin alphabet, used in the modern English alphabet, the alphabets of other western European languages and others worldwide. Its name in English is ''cee'' (pronounced ), plural ''cees''. History "C" ...
(TR1) first introduced them to the standard, as general utilities, but C++11 adds more functions, in line with the Boost version.


See also

*
Automatic Reference Counting Automatic Reference Counting (ARC) is a memory management feature of the Clang compiler providing automatic reference counting for the Objective-C and Swift programming languages. At compile time, it inserts into the object code messages retain a ...
* Resource acquisition is initialization (RAII) *
auto_ptr auto_ptr is a class template that was available in previous versions of the C++ standard library (declared in the header file), which provides some basic RAII features for C++ raw pointers. It has been replaced by the unique_ptr class. The au ...
*
Opaque pointer In computer programming, an opaque pointer is a special case of an opaque data type, a data type declared to be a pointer to a record or data structure of some unspecified type. Opaque pointers are present in several programming languages includi ...
*
Reference (computer science) In computer programming, a reference is a value that enables a program to indirectly access a particular data, such as a variable's value or a record, in the computer's memory or in some other storage device. The reference is said to refer t ...
*
Boost (C++ libraries) Boost is a set of libraries for the C++ programming language that provides support for tasks and structures such as linear algebra, pseudorandom number generation, multithreading, image processing, regular expressions, and unit testing. It c ...
*
Fat pointer In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
*
Garbage collection Waste collection is a part of the process of waste management. It is the transfer of solid waste from the point of use and disposal to the point of treatment or landfill. Waste collection also includes the curbside collection of recyclabl ...
in computer programming


References


Further reading

* * * {{cite web , url=http://www.drdobbs.com/184403837/ , title=The New C++: Smart(er) Pointers , author-first=Herb , author-last=Sutter , author-link=Herb Sutter , date=2002-08-01
Smart Pointers - What, Why, Which?
Yonat Sharon

John M. Dlugosz


External links




The C++ Standard Library - A Tutorial and Reference
' by Nicolai M. Josuttis







Articles with example C++ code Data types