Deitel & Associates, Inc. Logo

Back to
digg.png delicious.png blinkit.png furl.png
C++ How to Program, 5/e

© 2005
pages: 1500
Buy the Book!
Amazon logo
InformIT logo

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

A common programming practice is to allocate dynamic memory, assign the address of that memory to a pointer, use the pointer to manipulate the memory and deallocate the memory with delete when the memory is no longer needed. If an exception occurs after successful memory allocation but before the delete statement executes, a memory leak could occur. The C++ standard provides class template auto_ptr in header file <memory> to deal with this situation.

An object of class auto_ptr maintains a pointer to dynamically allocated memory. When an auto_ptr object destructor is called (for example, when an auto_ptr object goes out of scope), it performs a delete operation on its pointer data member. Class template auto_ptr provides overloaded operators * and -> so that an auto_ptr object can be used just as a regular pointer variable is. Figure 16.10 demonstrates an auto_ptr object that points to a dynamically allocated object of class Integer (Figs. 16.8–16.9).

Line 18 of Fig. 16.10 creates auto_ptr object ptrToInteger and initializes it with a pointer to a dynamically allocated Integer object that contains the value 7. Line 21 uses the auto_ptr overloaded -> operator to invoke function setInteger on the Integer object pointed to by ptrToInteger. Line 24 uses the auto_ptr overloaded * operator to dereference ptrToInteger, then uses the dot (.) operator to invoke function getInteger on the Integer object pointed to by ptrToInteger. Like a regular pointer, an auto_ptr’s -> and * overloaded operators can be used to access the object to which the auto_ptr points.

Because ptrToInteger is a local automatic variable in main, ptrToInteger is destroyed when main terminates. The auto_ptr destructor forces a delete of the Integer object pointed to by ptrToInteger, which in turn calls the Integer class destructor. The memory that Integer occupies is released, regardless of how control leaves the block (e.g., by a return statement or by an exception). Most importantly, using this technique can prevent memory leaks. For example, suppose a function returns a pointer aimed at some object. Unfortunately, the function caller that receives this pointer might not delete the object, thus resulting in a memory leak. However, if the function returns an auto_ptr to the object, the object will be deleted automatically when the auto_ptr object’s destructor gets called.

 1  // Fig. 16.8: Integer.h
 2  // Integer class definition.
 4  class Integer
 5  {
 6  public:
 7     Integer( int i = 0 ); // Integer default constructor
 8     ~Integer(); // Integer destructor
 9     void setInteger( int i ); // functions to set Integer
10     int getInteger() const; // function to return Integer
11  private:
12     int value;
13  }; // end class Integer

Fig. 16.8 Class Integer definition.

 1  // Fig. 16.9: Integer.cpp
 2  // Integer member function definition.
 3  #include <iostream>
 4  using std::cout;
 5  using std::endl;
 7  #include "Integer.h"
 9  // Integer default constructor
10  Integer::Integer( int i )
11     : value( i )
12  {
13     cout << "Constructor for Integer " << value << endl;
14  } // end Integer constructor
16  // Integer destructor
17  Integer::~Integer()
18  {
19     cout << "Destructor for Integer " << value << endl;
20  } // end Integer destructor
22  // set Integer value
23  void Integer::setInteger( int i )
24  {
25     value = i;
26  } // end function setInteger
28  // return Integer value
29  int Integer::getInteger() const
30  {
31     return value;
32  } // end function getInteger

Fig. 16.9 Member function definition of class Integer.

Additional Pages in this Tutorial: Page 1 | 2
Tutorial Index