Smart pointer
Encyclopedia
In computer science, a smart pointer is an abstract data type
that simulates a pointer while providing additional features, such as automatic garbage collection
or bounds checking
. These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency. Smart pointers typically keep track of the objects they point to for the purpose of memory management
.
The misuse of pointers is a major source of bugs: the constant allocation, deallocation and referencing that must be performed by a program written using pointers introduces the risk that memory leak
s will occur. Smart pointers try to prevent memory leaks by making the resource deallocation automatic: when the pointer (or the last in a series of pointers) to an object is destroyed, for example because it goes out of scope
, the pointed object is destroyed too.
Several types of smart pointers exist. Some work with reference counting
, others by assigning ownership of the object to a single pointer. If the language supports automatic garbage collection (for instance, Java
or C#), then this use of a smart pointer is unnecessary.
, smart pointers may be implemented as a template class that mimics, by means of operator overloading
, the behaviour of traditional (raw) pointers, (e.g.: dereferencing, assignment) while providing additional memory management algorithms.
Smart pointers can facilitate intentional programming
by expressing the use of a pointer in the type itself. For example, if a C++ function returns a pointer, there is no way to know whether the caller should delete the memory pointed to when the caller is finished with the information.
Traditionally, this has been solved with comments, but this can be error-prone. By returning an
the function makes explicit that the caller will take ownership of the result, and furthermore, that if the caller does nothing, no memory will be leaked.
The copy constructor and assignment operators of do not actually copy the stored pointer. Instead, they transfer it, leaving the previous object empty. This was one way to implement strict ownership, so that only one object could own the pointer at any given time. This means that should not be used where copy semantics are needed.
C++11 provides support for move semantics; it allows for the explicit support of transferring values as a different operation from copying them. C++11 also provided support for explicitly preventing an object from being copied. Since already existed with its copy semantics, it could not be upgraded to be a move-only pointer without breaking backwards compatibility with existing code. Therefore, C++11 introduced a new pointer type: .
This pointer type has its copy constructor and assignment operator explicitly deleted; it cannot be copied. It can be moved using , which allows one object to transfer ownership to another.
is still available, but it is deprecated
under C++11.
. TR1 first introduced them to the standard, but C++11 gives them additional functionality in line with the Boost version.
represents reference counted ownership of a pointer. Each copy of the same owns the same pointer. That pointer will only be freed if all instances of the in the program are destroyed.
A uses reference counting, so circular references are potentially a problem. To break up cycles, can be used to access the stored object. The stored object will be deleted if the only references to the object are references. therefore does not ensure that the object will continue to exist, but it can ask for the resource.
s. This means that multiple threads can safely store or objects that reference the same object. This only protects the reference count itself; it does not protect the object being stored by the smart pointer.
The above only applies when multiple threads have their own instances that are referring to the same object. In cases where multiple threads are accessing the same instance, C++11 provides a number of atomic functions for accessing and manipulating the .
Abstract data type
In computing, an abstract data type is a mathematical model for a certain class of data structures that have similar behavior; or for certain data types of one or more programming languages that have similar semantics...
that simulates a pointer while providing additional features, such as automatic garbage collection
Garbage collection (computer science)
In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program...
or bounds checking
Bounds checking
In computer programming, bounds checking is any method of detecting whether a variable is within some bounds before its use. It is particularly relevant to a variable used as an index into an array to ensure its value lies within the bounds of the array...
. These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency. Smart pointers typically keep track of the objects they point to for the purpose of memory management
Memory management
Memory management is the act of managing computer memory. The essential requirement of memory management is to provide ways to dynamically allocate portions of memory to programs at their request, and freeing it for reuse when no longer needed. This is critical to the computer system.Several...
.
The misuse of pointers is a major source of bugs: the constant allocation, deallocation and referencing that must be performed by a program written using pointers introduces the risk that memory leak
Memory leak
A memory leak, in computer science , occurs when a computer program consumes memory but is unable to release it back to the operating system. In object-oriented programming, a memory leak happens when an object is stored in memory but cannot be accessed by the running code...
s will occur. Smart pointers try to prevent memory leaks by making the resource deallocation automatic: when the pointer (or the last in a series of pointers) to an object is destroyed, for example because it goes out of scope
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them—or semantics...
, the pointed object is destroyed too.
Several types of smart pointers exist. Some work with reference counting
Reference counting
In computer science, reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object, block of memory, disk space or other resource...
, others by assigning ownership of the object to a single pointer. If the language supports automatic garbage collection (for instance, Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
or C#), then this use of a smart pointer is unnecessary.
C++ Smart Pointers
In C++C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
, smart pointers may be implemented as a template class that mimics, by means of operator overloading
Operator overloading
In object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...
, the behaviour of traditional (raw) pointers, (e.g.: dereferencing, assignment) while providing additional memory management algorithms.
Smart pointers can facilitate intentional programming
Intentional Programming
In computer programming, intentional programming is a collection of concepts which enable software source code to reflect the precise information, called intention, which programmers had in mind when conceiving their work...
by expressing the use of a pointer in the type itself. For example, if a C++ function returns a pointer, there is no way to know whether the caller should delete the memory pointed to when the caller is finished with the information.
Traditionally, this has been solved with comments, but this can be error-prone. By returning an
auto ptrAuto ptrauto_ptr is a class template available in the C++ Standard Library that provides some basic RAII features for C++ raw pointers....
,the function makes explicit that the caller will take ownership of the result, and furthermore, that if the caller does nothing, no memory will be leaked.
unique_ptr
C++11 provides .The copy constructor and assignment operators of do not actually copy the stored pointer. Instead, they transfer it, leaving the previous object empty. This was one way to implement strict ownership, so that only one object could own the pointer at any given time. This means that should not be used where copy semantics are needed.
C++11 provides support for move semantics; it allows for the explicit support of transferring values as a different operation from copying them. C++11 also provided support for explicitly preventing an object from being copied. Since already existed with its copy semantics, it could not be upgraded to be a move-only pointer without breaking backwards compatibility with existing code. Therefore, C++11 introduced a new pointer type: .
This pointer type has its copy constructor and assignment operator explicitly deleted; it cannot be copied. It can be moved using , which allows one object to transfer ownership to another.
is still available, but it is deprecated
Deprecation
In the process of authoring computer software, its standards or documentation, deprecation is a status applied to software features to indicate that they should be avoided, typically because they have been superseded...
under C++11.
shared_ptr and weak_ptr
C++11 incorporates and , based on versions used by the Boost librariesBoost library
Boost is a set of free software libraries that extend the functionality of C++.-Overview:Most of the Boost libraries are licensed under the Boost Software License, designed to allow Boost to be used with both free and proprietary software projects...
. TR1 first introduced them to the standard, but C++11 gives them additional functionality in line with the Boost version.
represents reference counted ownership of a pointer. Each copy of the same owns the same pointer. That pointer will only be freed if all instances of the in the program are destroyed.
A uses reference counting, so circular references are potentially a problem. To break up cycles, can be used to access the stored object. The stored object will be deleted if the only references to the object are references. therefore does not ensure that the object will continue to exist, but it can ask for the resource.
Concurrency issues
Operations that change the reference count, due to copying or destroying or objects, do not provoke data race conditionRace condition
A race condition or race hazard is a flaw in an electronic system or process whereby the output or result of the process is unexpectedly and critically dependent on the sequence or timing of other events...
s. This means that multiple threads can safely store or objects that reference the same object. This only protects the reference count itself; it does not protect the object being stored by the smart pointer.
The above only applies when multiple threads have their own instances that are referring to the same object. In cases where multiple threads are accessing the same instance, C++11 provides a number of atomic functions for accessing and manipulating the .
See also
- RAII (Resource Acquisition Is Initialization)
- auto ptrAuto ptrauto_ptr is a class template available in the C++ Standard Library that provides some basic RAII features for C++ raw pointers....
- Opaque pointerOpaque pointerIn computer programming, an opaque pointer is a special case of an opaque data type, a datatype that is declared to be a pointer to a record or data structure of some unspecified type....
- ReferenceReference (computer science)In computer science, a reference is a value that enables a program to indirectly access a particular data item, such as a variable or a record, in the computer's memory or in some other storage device. The reference is said to refer to the data item, and accessing those data is called...
- The Boost libraryBoost libraryBoost is a set of free software libraries that extend the functionality of C++.-Overview:Most of the Boost libraries are licensed under the Boost Software License, designed to allow Boost to be used with both free and proprietary software projects...
includes a reference-counting and intrusively-counted smart pointer implementation for C++
External links
- Sample chapter "Smart Pointers" from the book Modern C++ Design: Generic Programming and Design Patterns AppliedModern C++ DesignModern C++ Design: Generic Programming and Design Patterns Applied is a book written by Andrei Alexandrescu, published in 2001 by Addison-Wesley. It has been regarded as "one of the most important C++ books" by Scott Meyers ....
by Andrei AlexandrescuAndrei AlexandrescuAndrei Alexandrescu is a Romanian C++ programmer and author. He is particularly known for his pioneering work on policy-based design implemented via template metaprogramming. These ideas are articulated in his book Modern C++ Design and were first implemented in his programming library, Loki. He...
, Addison-Wesley, 2001. - Code example "countptr.hpp" from the book The C++ Standard Library - A Tutorial and Reference by Nicolai M. Josuttis
- "Boost Smart Pointers"
- Article "The New C++: Smart(er) Pointers" by Herb SutterHerb SutterHerb Sutter is a prominent C++ expert. He is also a book author and a columnist for Dr. Dobb's Journal. He joined Microsoft in 2002 as a platform evangelist for Visual C++ .NET, rising to lead software architect for C++/CLI. Sutter served as secretary and convener of the ISO C++ standards committee...
August 1, 2002 - "Smart Pointers - What, Why, Which?" by Yonat Sharon
- "Smart Pointers Overview" by John M. Dlugosz
- The YASPER library Yet Another Smart Pointer implementation in C++
- Smart Pointers in Delphi