One of the most common programming errors among C and C++ programmers occurs when dynamic memory allocated with new is not deallocated properly with delete, which causes dangerous memory leaks in applications. This tutorial presents the C++ standard library class template auto_ptr, which helps programmers manage dynamic memory. An auto_ptr object "looks like" a pointer (i.e., it has the same semantics), but when it goes out of scope it automatically deletes the dynamic memory it manages. Thus, auto_ptrs help defend against memory leaks. auto_ptr objects also provide a means to transfer ownership of dynamic memory. This tutorial is intended for students and professionals who are already familiar with C++ memory management and know how to create objects with class templates.
Download the code examples for this tutorial.
[Note: This tutorial is an excerpt (Section 16.12) of Chapter 16, Exception Handling, from our textbook C++ How to Program, 5/e. These tutorials may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., C++ HOW TO PROGRAM, ©2005, pp.829-832. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]
16.12 Class auto_ptr and Dynamic Memory Allocation (Continued)
Output
Creating an auto_ptr object that points to an Integer Constructor for Integer 7 Using the auto_ptr to manipulate the Integer Integer after setInteger: 99 Terminating program Destructor for Integer 99 |
Fig. 16.10 auto_ptr object manages dynamically allocated memory.
An auto_ptr can pass ownership of the dynamic memory it manages via its overloaded assignment operator or copy constructor. The last auto_ptr object that maintains the pointer to the dynamic memory will delete the memory. This makes auto_ptr an ideal mechanism for returning dynamically allocated memory to client code. When the auto_ptr goes out of scope in the client code, the auto_ptr’s destructor deletes the dynamic memory.
![]() |
Software Engineering Observation 16.9 |
An auto_ptr has restrictions on certain operations. For example, an auto_ptr cannot point to an array or a standard-container class. |


