Thursday, March 8, 2012

What is smart pointer?

The main problems with pointers in C/C++ is handling memory managment. Most of the bugs related to memory leaks and dangling pointers. To overcome this C++ supports smart pointers. The smart pointer is a object similar to pointer. Smart pointer supports all basic operations like dereferencing(operator *), indirection (operator ->)  and below features which pointer doesn't support.

Automatic deallocation: Smart pointer deallocates/cleanup the allocated memory automatically using destructor.
Automatic initialisation: No need to initialise the pointer to NULL. smart pointer will take care using constructor
Handling Dangling pointers: One of the main problem in C/C++ is handling dagling pointer. i.e. accessing the pointer that is pointing to the another object which is already deleted. Smart pointers will take care about dangling pointers.

P.S: Simple example for the smart pointers in C++ is auto_ptr which is a part of C++ standard library. And the header file is .

No comments:

Popular Posts