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
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
substr() in C++
In C++, the string substr() function is used to extract a substring from the given string. It generates a new string with its value initialized to a copy of a sub-string of the given string.Example:C++#include <iostream> #include <string> using namespace std; int main() { // Take any str
3 min read
strcpy in C++
strcpy() is a standard library function in C++ and is used to copy one string to another. In C++ it is present in the <string.h> and <cstring> header files. Syntax: char* strcpy(char* dest, const char* src);Parameters: This method accepts the following parameters: dest: Pointer to the de
2 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. If the character is found, it returns the pointer to its first occurrence oth
3 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++
In C++, unique_ptr is a smart pointer that manages a dynamically allocated object, and it was introduced in C++11. It is defined in the <memory> header file. Here are the key points about unique_ptr:Ownership: unique_ptr owns the object it points to. Only one unique_ptr can own an object at a
4 min read
Pointers vs Array in C++
Arrays and pointers are two derived data types in C++ that have a lot in common. In some cases, we can even use pointers in place of arrays. But even though they are so closely related, they are still different entities. In this article, we will study how the arrays and pointers are different from e
3 min read