Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain smart pointers in plain English?

Today I was asked about smart pointers in C++, and I can't find anywhere useful information about it..

Please, can someone tell: What is smart pointers? When do you need it? Do you have any example where smart pointers is actually useful?

Thank you!

like image 999
VextoR Avatar asked Feb 15 '11 14:02

VextoR


2 Answers

Primarily, smart pointers help you to:

  • Avoid leaks when exceptions are thrown. When an exception is thrown, you don't want any objects that are allocated earlier in the try block to be leaked. By wrapping them in smart pointers, which will be destroyed when the try block is exited, those objects will get properly destroyed.
  • Manage lifetime by reference counting owners to objects (i.e., the last one to destroy its smart pointer referencing a particular object actually deallocates the object). This is especially helpful in loosely coupled scenarios where it is not clear at what time the object should be destroyed, because users of the object do not know about each other.

A good example of where smart pointers are useful:

A vector of pointers to objects. By making it a vector of shared pointers, for example, the objects will automatically be deallocated when the vector is destroyed and/or objects are removed. This automates object lifetime management and helps the user of the container avoid memory leaks.

like image 119
Michael Goldshteyn Avatar answered Sep 20 '22 22:09

Michael Goldshteyn


Excerpt from Boost Smart Pointers (smart_ptr) lib:

Smart pointers are objects which store pointers to dynamically allocated (heap) objects. They behave much like built-in C++ pointers except that they automatically delete the object pointed to at the appropriate time. Smart pointers are particularly useful in the face of exceptions as they ensure proper destruction of dynamically allocated objects. They can also be used to keep track of dynamically allocated objects shared by multiple owners.

Conceptually, smart pointers are seen as owning the object pointed to, and thus responsible for deletion of the object when it is no longer needed.

like image 37
Andrejs Cainikovs Avatar answered Sep 18 '22 22:09

Andrejs Cainikovs