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
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read