Use of auto_ptr? I can't find one.
Hello,
i read a bit about stl::auto_ptr. Most tutorials show the big advantages refering to exception safety and avoiding memory leaks on an example like this:
Code:
void foo()
{
T* t = new T();
// exception
delete t;
}
So here someone allocate heap in a function foo and deallocate it before t is going out of scope and the memory is lost.
The better way should be:
Code:
void foo()
{
auto_ptr<T*> t( new T() );
// exception
// t is auto freed while going out of scope
}
My question what hold my awake this night is:
Why should someone declare a pointer T* and allocate heap, if he just delete it at the and of the same scope? The sens, for my understanding, of declaring a pointer and allocating heap is to append the live of a fraction of memory beyond the actual scope?!
So nobody would use the about example but just write:
Code:
void foo()
{
T t();
// exception
// t is auto freed while going out of scope
}
or, if t should be available outside the scope of foo:
Code:
T* foo()
{
T* t = new T();
return t;
}
What did I get wrong, where is the reasonable sens of auto_ptr?
Thanks in advance.