Smart Pointers Explained With Simple Example

Standard library included with C++ compilers provides some specific resource management pointers classes which are also called as Smart Pointers.

A normal (raw) pointer typically points to an object, but it doesn’t indicate who owns the objects. This leads to the confusion most of the times, that who is supposed to delete the pointer and free the memory.
Also, by looking into the pointer, one can’t guess how the pointer should be deleted.

Smart pointers are designed to overcome these shortcomings of raw pointers.

Types of Smart Pointers

  • unique_ptr -> This pointer class has the exclusive ownership.
  • shared_ptr -> This pointer class has the shared ownership.
  • weak_ptr -> This pointer class is used with shared_ptr and it doesn’t have any ownership. This pointer is typically used to break loops into circular data structures.
(more…)
Smart Pointers Explained With Simple Example Read More