Exception Handling in C++

This page might seem like it duplicates some of what we have just seen, but it is valuable because it gives a different perspective on the topic. Read chapter 1 on pages 15-60.

Cleaning up

auto_ptr

Since dynamic memory is the most frequent resource used in a typical C++ program, the standard provides an RAII wrapper for pointers to heap memory that automatically frees the memory. The auto_ptr class template, defined in the <memory> header, has a constructor that takes a pointer to its generic type (whatever you use in your code). The auto_ptr class template also overloads the pointer operators * and -> to forward these operations to the original pointer the auto_ptr object is holding. So you can use the auto_ptr object as if it were a raw pointer. Here's how it works:

//: C01:Auto_ptr.cpp
// Illustrates the RAII nature of auto_ptr.
#include 
#include 
#include 
using namespace std;
 
class TraceHeap {
  int i;
public:
  static void* operator new(size_t siz) {
    void* p = ::operator new(siz);
    cout << "Allocating TraceHeap object on the heap "
         << "at address " << p << endl;
    return p;
  }
  static void operator delete(void* p) {
    cout << "Deleting TraceHeap object at address "
         << p << endl;
    ::operator delete(p);
  }
  TraceHeap(int i) : i(i) {}
  int getVal() const { return i; }
};
 
int main() {
  auto_ptr pMyObject(new TraceHeap(5));
  cout << pMyObject->getVal() << endl;  // Prints 5
} ///:~
The TraceHeap class overloads the operator new and operator delete so you can see exactly what's happening. Notice that, like any other class template, you specify the type you're going to use in a template parameter. You don't say TraceHeap*, however ­– auto_ptr already knows that it will be storing a pointer to your type. The second line of main( ) verifies that auto_ptr's operator->( ) function applies the indirection to the original, underlying pointer. Most important, even though we didn't explicitly delete the original pointer, pMyObject's destructor deletes the original pointer during stack unwinding, as the following output verifies:
Allocating TraceHeap object on the heap at address 8930040
5
Deleting TraceHeap object at address 8930040
The auto_ptr class template is also handy for pointer data members. Since class objects contained by value are always destructed, auto_ptr members always delete the raw pointer they wrap when the containing object is destructed.