There are some cases when you might need auto_ptr. For example:
Code:
void f() {
MyClass* p = new MyClass;
p->DoSomething(); // might throw
delete p;
}
If MyClass::DoSomehing throws then you get a memory leak. One way to fix this is:
Code:
void f() {
MyClass* p = new MyClass;
try {
p->DoSomething();
delete p;
} catch(...) {
delete p;
throw;
}
}
auto_ptr makes this easier:
Code:
void f() {
auto_ptr<MyClass> p(new MyClass);
p->DoSomething();
}
Even if MyClass::DoSomething throws you are guaranteed to have p deleted because auto_ptr's destructor is called.