C++ – Smart Pointers

In C++, memory allocated from heap has to be freed manually. But there could be situations where the programmer forgets to deallocate the memory and causes what is known as memory leakage.

Smart Pointers in C++ are wrapper template classes for pointers that conforms to RAII principle and releases the memory when they go out of scope. This is done by allocating the memory in the constructor and freeing it in the destructor. Operators including ‘*’ and ‘->’ have been overloaded within these classes. Smart Pointers were introduced into the standard in C++ 11 and are available within the ‘memory’ header.

There are three types of Smart Pointers in C++. Unique_ptr, Shared_ptr and Weak_ptr.

A Unique_ptr object maintains exclusive ownership to the heap memory it holds. When the unique_ptr object goes out of scope, the heap memory held by it is released. The only way to give another unique_ptr access to this memory is via the move operation.

Shared_ptr objects share the ownership to the heap memory. Memory is freed only when all the owners go out of scope.


Output:

4
4

Weak_ptr are used along with shared_ptr. They are used to get a pointer to a memory location without taking the ownership of it. Weak pointers are usually used to remove cyclic dependencies, solve dangling pointer problems etc. The member methods, expired() and lock() are used to work with weak pointers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s