Home C C++ Java Python Perl PHP SQL JavaScript Linux Selenium QT Online Test

Home » C++ » Smart Pointers in C++

Smart Pointers in C++ with Examples


Issues with Smart Pointers:-

1. C++ 98 auto_ptr is smart. But it has more fundamental flaws over its smartness. auto_ptr transfers the ownership when it is assigned to another auto_ptr This is really an issue while passing the auto_ptr between the functions.
2. We can't use auto_ptr with an array of objects
     auto_ptr ptr (new Class[5])
3. We can't use auto_ptr with STL like Map, MultiMap, Vector, List , Set etc..

As C++ 98 has many issues so C++ 11 introduced new set of smart pointers

  • shared_ptr
  • unique_ptr
  • weak_ptr

Shared_ptr :-
The Objective of shared_ptr is to allow multiple shared pointers to point a single object and when the last shared pointer goes out of scope, memory is released automatically.

Weak_ptr :-
A weak pointer provides sharing semantics and not owning semantics. This means a weak pointer can share a resource held by a shared_ptr. So to create a weak pointer, some body should already own the resource which is nothing but a shared pointer.

A weak pointer does not allow normal interfaces supported by a pointer, like calling *, ->. Because it is not the owner of the resource and hence it does not give any chance for the programmer to mishandle it. Then how do we make use of a weak pointer?

The answer is to create a shared_ptr out of a weak _ptr and use it. Because this makes sure that the resource will no be destroyed while using by incrementing the strong reference count. As the reference count is incremented, it is sure that the count will be at least 1 till you complete using the shared_ptr created out of the weak_ptr. Otherwise what may happen is while using the weak_ptr, the resource held by the shared_ptr goes out of scope and the memory is released which creates chaos.


int main()
{ 
 shared_ptr<ClassName> sptr( new ClassName );
 weak_ptr<ClassName> wptr( sptr );
 weak_ptr<ClassName> wptr1 = wptr;
 return 0;<br>
}

Unique_ptr :-
This is to overcome issues with the error prone auto_ptr. unique_ptr follows the exclusive ownership semantics, i.e., at any point of time, the resource is owned by only one unique_ptr. When unique_ptr goes out of scope, the resource is released. If the resource is overwritten by some other resource, the previously owned resource is released. So it guarantees that the associated resource is released always. We can use std::move to change the owner ship. Very good example of unique_ptr Click here


unique_ptr<int> uptr( new int );
unique_ptr<int[ ]> uptr( new int[5] );
Questions on C++ Pointers