cppbuzz logo

Home  |  About Us  |  Contact
View Questions Upload Training Misc..

Smart Pointers in C++

Issues with Smart Pointes:-
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 intorduced new set of smart pointers:-

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 sptr( new ClassName );
weak_ptr wptr( sptr );
weak_ptr wptr1 = wptr;
return 0;

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.

unique_ptr uptr( new int );
unique_ptr uptr( new int[5] );