C++ Tutorial - Class auto_ptr
auto_ptr type is provided by the C++ standard library as a sort of smart pointer that helps to avoid resource leaks when exceptions are thrown.
Here is a typical example which has potential of memory leak.
void memory_leak() { ClassA * ptr = new ClassA; ... delete ptr; }
The reason why this function is source of trouble is that the deletion of the object might be forgotten especially if we have return inside of it. Also an exception would exit the function before the delete statement at the end of the function causing a resource leak.
Usually, we do try to capture all exceptions as in the example below.
void memory_leak() { ClassA * ptr = new ClassA; try { ... } catch(...) { delete ptr; throw; } delete ptr; }
As we see in the example, trying to handle the deletion of this object properly in the event of an exception makes the code more complicated and redundant.
So, we need a pointer which can free the data to which it points whenever the pointer itself gets destroyed. Because the pointer is a local variable, it will be destroyed automatically when the function is exited regardless of whether the exit is normal or caused by an exception.
In other words, 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.
Our auto_ptr is a pointer that serves as owner of the object to which it refers. So, an object gets destroyed automatically when its auto_ptr gets destroyed.
The function in the 1st example can be rewritten using auto_ptr
#include <memory> void memory_leak() { std::auto_ptr<ClassA> ptr(new ClassA); ... }
The delete statement and catch clause are no longer needed.
An auto_ptr has the same interface as an ordinary pointer. Operator * dereferences the object and operator -> provides access to a member if the object is a class or a structure.
But the pointer arithmetic such as ++ is not defined.
One more thing we should be careful about the usage of the pointer is that auto_ptr does not allow us to initialize an object with an ordinary pointer by using the assignment syntax. So, we must initialize the auto_ptr directly by using its value.
std::auto_ptr<ClassA> ptr1(new ClassA); // RIGHT std::auto_ptr<ClassA> ptr1 = new ClassA; // WRONG
Here is the example of auto_ptr in action:
#include <iostream> #include <memory> using namespace std; class Double { public: Double(double d = 0) : dValue(d) { cout << "constructor: " << dValue << endl; } ~Double() { cout << "destructor: " << dValue << endl; } void setDouble(double d) { dValue = d; } private: double dValue; }; int main() { auto_ptr<Double> ptr(new Double(3.14)); (*ptr).setDouble(6.28); return 0; }
The example creates auto_ptr object ptr and initializes it with a pointer to a dynamically allocated Double object.
Because ptr is a local automatic variable in main(), ptr is destroyed when main terminates. The auto_ptr destructor forces a delete of the Double object pointed to by ptr, which in turn calls the Double class destructor. The memory that Double occupies is released. The Double object will be deleted automatically when the auto_ptr object's destructor gets called.
Only one auto_ptr at a time can own a dynamically allocated object. Thus, the object cannot be an array. By using its overloaded assignment operator or copy constructor, an auto_ptr can transfer ownership of the dynamic memory it manages. 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.
Though std::auto_ptr is responsible for managing dynamically allocated memory and automatically calls delete to free the dynamic memory when the auto_ptr is destroyed or goes out of scope, auto_ptr have some limitations.
- An auto_ptr can't point to an array. When deleting a pointer to an array we must use delete[] to ensure that destructors are called for all objects in the array, but auto_ptr uses delete.
- It can't be used with the STL containers-elements in an STL container. When an auto_ptr is copied, ownership of the memory is transferred to the new auto_ptr and the original is set to NULL. In other words, auto_ptrs don't work in 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. An STL container may make copies of its elements, so you can't guarantee that a valid copy of the auto_ptr will remain after the algorithm processing the container's elements finishes.
An auto_ptr is simply an object that holds a pointer for us within a function. Holding a pointer to guarantee deletion at the end of a scope is what auto_ptr is for, and for other uses requires very specialized skills from a programmer.
The Boost.Smart_ptr library provides additional smart pointers to fill in the gaps where auto_ptrs don't work. TR1 includes two of the six types of smart pointers in the Boost.Smart_ptr library, namely shared_ptr and weak_ptr. These smart pointers are not meant to replace auto_ptr. Instead, they provide additional options with different functionality.
For more on auto_ptr, see smart pointers
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization