Smart pointer
Encyclopedia
In computer science, a smart pointer is an abstract data type
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.

some_type* ambiguous_function; // What should be done with the result?

Traditionally, this has been solved with comments, but this can be error-prone. By returning an auto ptr
Auto ptr
auto_ptr is a class template available in the C++ Standard Library that provides some basic RAII features for C++ raw pointers....

,

auto_ptr obvious_function1;

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.


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 rendered invalid.

p3.reset; //Deletes the memory.
p1.reset; //Does nothing.


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 libraries
Boost 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.


std::shared_ptr p1(new int(5));
std::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 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.


std::shared_ptr p1(new int(5));
std::weak_ptr wp1 = p1; //p1 owns the memory.

{
std::shared_ptr p2 = wp1.lock; //Now p1 and p2 own the memory.
if(p2) //Always check to see if the memory still exists
{
//Do something with p2
}
} //p2 is destroyed. Memory is owned by p1.

p1.reset; //Memory is deleted.

std::shared_ptr p3 = wp1.lock; //Memory is gone, so we get an empty shared_ptr.
if(p3)
{
//Will not execute this.
}

Concurrency issues

Operations that change the reference count, due to copying or destroying or objects, do not provoke data race condition
Race 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 ptr
    Auto ptr
    auto_ptr is a class template available in the C++ Standard Library that provides some basic RAII features for C++ raw pointers....

  • Opaque pointer
    Opaque pointer
    In 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....

  • Reference
    Reference (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 library
    Boost 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...

     includes a reference-counting and intrusively-counted smart pointer implementation for C++

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK