Smart pointer

Smart pointer

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 that point to them 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 makes it very likely that some memory leaks will occur. Smart pointers try to prevent memory leaks by making the resource deallocation automatic: when the pointer to an object (or the last in a series of pointers) 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 assigning ownership of the object to a single pointer. If the language supports automatic garbage collection (for instance, Java), then this use of a smart pointer is unnecessary.

In C++ language, 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. 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 a C++ auto_ptr, auto_ptr obvious_function1();the function makes explicit that the caller will take ownership of the result, and further more, that if the caller does nothing, no memory will be leaked. Similarly, if the intention is to return a pointer to an object managed elsewhere, the function could return by reference: some_type& obvious_function2();

Example

Let SmartPointer be a template smart pointer for memory management of class X instances through reference counting.

void test_smartpointers() { //first, we create two objects and we keep raw pointers to them //since these pointers are not smart, they will not affect the object lifecycle //notice that if obj_2 throws a memory allocation error, obj_1 will not be destroyed // because it isn't held by a smart pointer yet

Object* obj_1 = new Object(); Object* obj_2 = new Object();

//then we declare two smart pointers and we assign them with the objects //both obj_1 and obj_2 will have counter=1 SmartPointer p = obj_1; SmartPointer q = obj_2;

//now we assign p into q, yielding obj_1.counter=2 //obj_2 will be destroyed because its counter reaches 0 q = p;

//we assign q with NULL //obj_1.counter reaches 1 q = NULL;

//now we create a new object, and we assign its address to the smart pointer //it will be automatically destroyed before leaving the scope //obj_1 will be destroyed because its counter reaches 0 p = new Object();

//finally, we create another object which will be only referenced by a raw pointer. //obj_3 will be lost and there will be a memory leak Object* obj_3 = new Object(); }

See also

* auto_ptr
* Opaque pointer
* Reference
* The Standard Template Library includes a smart pointer for C++
* The Boost library includes a reference-counting smart pointer implementation for C++

External links

*Sample chapter " [http://www.informit.com/articles/article.aspx?p=25264 Smart Pointers] " from the book " [http://www.moderncppdesign.com/ Modern C++ Design: Generic Programming and Design Patterns Applied] " by Andrei Alexandrescu, Addison-Wesley, 2001.
*Code example " [http://www.josuttis.com/libbook/cont/countptr.hpp.html countptr.hpp] " from the book " [http://www.josuttis.com/libbook/ The C++ Standard Library - A Tutorial and Reference] " by Nicolai M. Josuttis
*Article " [http://cuj.com/documents/s=8470/cuj0204karlsson/ Smart Pointers in Boost] " [http://boost.org/libs/smart_ptr/smart_ptr.htm]
*Article " [http://cuj.com/documents/s=7980/cujcexp2008sutter/ The New C++: Smart(er) Pointers] " by Herb Sutter
*" [http://ootips.org/yonat/4dev/smart-pointers.html Smart Pointers - What, Why, Which?] " by Yonat Sharon
*" [http://dlugosz.com/Repertoire/refman/Classics/Smart%20Pointers%20Overview.html Smart Pointers Overview] " by John M. Dlugosz
* The [http://yasper.sourceforge.net/ YASPER library] Yet Another Smart Pointer implementation in C++
* [http://barrkel.blogspot.com/2008/09/smart-pointers-in-delphi.html Smart Pointers in Delphi]

Wikimedia Foundation. 2010.

Look at other dictionaries:

  • Smart pointer — Умный указатель (англ. smart pointer) класс (обычно шаблонный), имитирующий интерфейс обычного указателя и добавляющий некую новую функциональность, например проверку границ при доступе или очистку памяти. Содержание 1 Владеющие указатели 1.1… …   Википедия

  • Smart Pointer — Intelligente Zeiger oder Smart Pointers werden in vielen gängigen objektorientierten Programmiersprachen, meistens C++, verwendet. Es sind spezielle Objekte, welche einfache Zeigervariablen einkapseln und mit zusätzlichen Funktionen und… …   Deutsch Wikipedia

  • Smart pointer — Intelligente Zeiger oder Smart Pointers werden in vielen gängigen objektorientierten Programmiersprachen, meistens C++, verwendet. Es sind spezielle Objekte, welche einfache Zeigervariablen einkapseln und mit zusätzlichen Funktionen und… …   Deutsch Wikipedia

  • Pointer (computing) — This article is about the programming data type. For the input interface (for example a computer mouse), see Pointing device. Pointer a pointing to the memory address associated with variable b. Note that in this particular diagram, the computing …   Wikipedia

  • Pointer overflow — Pufferüberläufe (engl. buffer overflow) gehören zu den häufigsten Sicherheitslücken in aktueller Software, die sich u. a. über das Internet ausnutzen lassen können. Im Wesentlichen werden bei einem Pufferüberlauf durch Fehler im Programm zu große …   Deutsch Wikipedia

  • Pointer (Informatik) — Mit Zeiger oder Pointer wird in der Informatik eine spezielle Variable bezeichnet, die auf eine andere Variable oder Funktion verweist. Der referenzierte Speicherbereich enthält entweder Daten (Objekt, Variable) oder Programmcode. Zeiger auf… …   Deutsch Wikipedia

  • Dangling pointer — Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type. These are special cases of memory safety violations. Dangling Pointer Dangling pointers arise when an object is… …   Wikipedia

  • Stanford Smart Memories Project — Advances in VLSI technology now permit multiple processors to reside on a single integrated circuit chip, or IC. Such a processing system is known as a chip multiprocessor, or multi core CPU system. Building on this technology, the Stanford Smart …   Wikipedia

  • Maxwell Smart (record producer) — Maxwell Smart Birth name Max Perry Born June 23, 1984 (1984 06 23) (age 27) Origin Brooklyn, New York, United States Genres …   Wikipedia

  • Puntero inteligente — En programación, un puntero inteligente (o smart pointer) es un tipo abstracto de datos que simula el comportamiento de un Puntero (informática) pero añadiendo nuevas características adicionales, como recolector de basura automático y comprobador …   Wikipedia Español

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”