Auto Pointer (auto_ptr) in C++
auto_ptr is a smart pointer that manages an object obtained via a new expression and deletes that object when auto_ptr itself is destroyed. Once the object is destroyed, it de-allocates the allocated memory. auto-ptr has ownership control over the object and it is based on the Exclusive Ownership Model, which says that a memory block can not be pointed by more than one pointer of the same type.
When an object is defined using auto_ptr, it stores a pointer to the allocated object and ensures that when the auto_ptr itself gets out of scope, the memory it is pointing to also gets destroyed.
Syntax of auto_ptr
The auto pointer in C++ is defined as:
auto_ptr <type> pointer_name = value;
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