Rather than trying to understand auto_ptr
and its relation to garbage-collected references, you should really try to see the underlying pattern:
In C++, all local objects have their destructors called when they go out of scope. This can be harnessed to clean up memory. For example, we could write a class which, in its constructor, is given a pointer to heap-allocated memory, and in its destructor, frees this pointer.
That is pretty much what auto_ptr
does. (Unfortunately, auto_ptr
also has some notoriously quirky semantics for assignment and copying)
It's also what boost::shared_ptr
or other smart pointers do. There's no magic to any of those. They are simply classes that are given a pointer in their constructor, and, as they're typically allocated on the stack themselves, they'll automatically go out of scope at some point, and so their destructor is called, which can delete the pointer you originally passed to the constructor. You can write such classes yourself. Again, no magic, just a straightforward application of C++'s lifetime rules: When a local object goes out of scope, its destructor is called.
Many other classes cut out the middleman and simply let the same class do both allocation and deallocation. For example, std::vector
calls new
as necessary to create its internal array -- and in its destructor, it calls delete
to release it.
When the vector is copied, it takes care to allocate a new array, and copy the contents from the original one, so that each object ends up with its own private array.
auto_ptr
, or smart pointers in general, aren't the holy grail. They don't "solve" the problem of memory management. They are one useful part of the recipe, but to avoid memory management bugs and headaches, you need to understand the underlying pattern (commonly known as RAII) -- that is, whenever you have a resource allocation, it should be tied to a local variable which is given responsibility for also cleaning it up.
Sometimes, this means calling new
yourself to allocate memory, and then passing the result to an auto_ptr
, but more often, it means not calling new
in the first place -- simply create the object you need on the stack, and let it call new
as required internally. Or perhaps, it doesn't even need to call new
internally. The trick to memory management is really to just rely on local stack-allocated objects instead of heap allocations. Don't use new
by default.