Why do we need auto_ptr?
The aim of using auto_ptr was to prevent resource or memory leaks and exceptions in the code due to the use of raw pointers. Let’s see an example of a memory leak. Consider the following code:
C++
void memLeak() { classA *ptr = new classA(); // some code delete ptr; } |
In this above code, we have used delete to deallocate the memory to avoid memory leaks. But what if an exception happens before reaching the delete statement? In this case, the memory will not be deallocated. Hence, there is a need for a pointer that can free the memory it is pointing to after the pointer itself gets destroyed.
The above example can be re-written using auto_ptr as :
C++
void memLeakPrevented() { auto_ptr<classA> ptr( new classA()); // some code } |
The delete statement is no longer required while using auto_ptr.
Note: The arithmetic functions on pointers are not valid for auto_ptr such as increment & decrement operators.
auto_ptr in C++
In C++, a memory leak may occur while de-allocating a pointer. So to ensure that the code is safe from memory leaks and exceptions, a special category of pointers was introduced in C++ which is known as Smart Pointers. In this article, we will discuss the auto pointer(auto_ptr) which is one of the smart pointers in C++.
Pre-Requisite: Pointer in C++, Smart Pointers in C++
Note: Auto Pointer was deprecared in C++11 and removed in C++17