Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
The class template std::auto_ptr is deprecated [5]. The class template std::unique_ptr provides a better solution [5].
std::auto_ptr is a smart pointer that deletes the instance it points to when going out of scope. It is supplied in the STL header file memory.h.
std::auto_ptr helps to:
Note: when you use a lot of forward declarations, you might want to prefer boost::scoped_ptr as it uses boost::checked_delete. Also, boost::scoped_ptr cannot be copied, so you will nearly ever be amazed by 'strange' behaviour.
Standard pointer:
struct MyClass {}; |
Using an auto_ptr:
#include <memory> |
Use objects to manage resources (like dynamically allocated memory)[2] and store newed objects in smart pointers in standalone statements [3].
std::auto_ptr's does more then saving you a delete statement. It ensures that the instance pointed to is only pointed to once. This is done by a non-symettric copy: when you pass a pointer from std::auto_ptr to std::auto_ptr, the original possessor gets zero. This is demonstrated below:
#include <memory> |
To get a copy to the pointed instance use the std::auto_ptr<T>::get member function:
#include <cassert> |
Also, using a std::auto_ptr, it gets clear which class manages the deletion of the pointed instance.
class Something{}; |
If the instance pointed to needs to be give to another class, then MyClass::GetSomething is left with an empty (that is: 0) pSomething.
When you create a new instance dynamically in a certain function using a plain pointer, in the end of this function you call delete. But when in the middle an exception is thrown, this delete is not called anymore! When using an auto_ptr, the instance DOES get deleted. This is because auto_ptr's delete their instances when they go out of scope.
This will give you a memory leak, as a std::auto_ptr calls delete, instead of delete[]. As advised by [1], you should prefer a std::vector over an array. But if you really want to use a smart pointer, use a boost::scoped_array.
A copy of a std::auto_ptr does not copy the memory address pointed to. Therefore, when using e.g. a sorting algorithm, some pointed instances might get deleted! Instead, use a boost::shared_ptr.
Resetting a std::auto_ptr first constructs a new instance of the class before deleting the old instance. This is demonstrated by the code below:
#include <iostream> |
This gives the following output:
Constructor |
The reason for this behavior is I guess- exception safety: if the allocation of the new resources fail, then the old resources are not yet released.
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.