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
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;
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.
Example of auto_ptr in C++
C++
// C++ program to illustrate the use of auto_ptr
#include <iostream>
#include <memory>
using namespace std;
// creating class with overloaded constructor and destructor
class Integer {
public:
Integer() { cout << "Object Created" << endl; }
~Integer() { cout << "Object Destroyed" << endl; }
};
// driver code
int main()
{
// creating auto pointer to Integar class
auto_ptr<Integer> ptr(new Integer());
// not using delete
return 0;
}
OutputObject Created
Object Destroyed
In this example, we have created an auto_ptr object ptr and initialized it with a pointer to a dynamically allocated Integer object.
As ptr is a local automatic variable in main(), ptr is destroyed when main() terminates. The auto_ptr destructor forces a delete of the Integer object pointed to by ptr, which in turn calls the Integer class destructor. The memory that the Integer occupies is released. The Integer object will be deleted automatically when the auto_ptr object's destructor gets called.
Why was auto_ptr removed?
auto_ptr was depreciated in C++ 11 and removed in C++ 17. The removal of the auto_ptr was due to the following limitations:
- An auto_ptr can't be used to point to an array. While deleting the pointer to an array, we need to use delete[] but in auto_ptr we can only use delete.
- An auto_ptr can not be used with STL Containers because the containers, or algorithms manipulating them, might copy the stored elements. Copies of auto_ptrs aren't equal because the original is set to NULL after being copied.
- The auto_ptr does not fit in the move semantics as they implement move by using copy operation.
Due to the above limitations, auto_ptr was removed from C++ and later replaced with unique_ptr.
Similar Reads
weak_ptr in C++
The weak_ptr is one of the smart pointers that provide the capability of a pointer with some reduced risks as compared to the raw pointer. The weak_ptr, just like shared_ptr has the capability to point to the resource owned by another shared_ptr but without owning it. In other words, they are able t
3 min read
Binary Tree in C++
A binary tree is a hierarchical data structure in which each node has at most two children, referred to as the left and right child. The topmost node is the root node, and the nodes at the last level having no children are the leaf nodes. In this article, we will learn about the basics of a binary t
13 min read
strstr() in C/C++
In C/C++, std::strstr() is a predefined function used for string matching. <string.h> is the header file required for string functions. This function takes two strings s1 and s2 as arguments and finds the first occurrence of the string s2 in the string s1. The process of matching does not incl
3 min read
vTable And vPtr in C++
In C++, runtime polymorphism is realized using virtual functions. But have you ever wondered how virtual functions work behind the scenes? The C++ language uses Vtable and Vptr to manage virtual functions. In this article, we will understand the concepts of Vtable and Vptr in C++. Prerequisites: C++
4 min read
Application of Pointer in C++
In C++, pointer is a variable that stores the memory address as its value. It is a powerful feature that forms the backbone of lower-level memory manipulation in C++. It is used in a variety of applications. Some of the common applications of pointers are discussed in this article. 1. Pass Arguments
4 min read
Function Pointer in C++
Prerequisites: Pointers in C++Function in C++ Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of point
4 min read
STD::array in C++
The array is a collection of homogeneous objects and this array container is defined for constant size arrays or (static size). This container wraps around fixed-size arrays and the information of its size are not lost when declared to a pointer. In order to utilize arrays, we need to include the ar
5 min read
strchr in C
The strchr() function in C is a predefined function in the <string.h> library. It is used to find the first occurrence of a character in a string. It checks whether the given character is present in the given string or not, if the character is found it returns the pointer to it otherwise it re
4 min read
shared_ptr in C++
std::shared_ptr is one of the smart pointers introduced in C++11. Unlike a simple pointer, it has an associated control block that keeps track of the reference count for the managed object. This reference count is shared among all the copies of the shared_ptr instances pointing to the same object, e
5 min read
Unique_ptr in C++
std::unique_ptr is a smart pointer introduced in C++11. It automatically manages the dynamically allocated resources on the heap. Smart pointers are just wrappers around regular old pointers that help you prevent widespread bugs. Namely, forgetting to delete a pointer and causing a memory leak or ac
4 min read