-
Using auto_ptr :: C++
Hi.
Under what situation should one use auto_ptr instead of plain pointer? I am in a situation where I cannot decide on using auto_ptr or pointer. I like auto_ptr because I trust that if something goes wrong at run-time, auto_ptr will help eliminate possible memory leaks. When do you recommend using auto_ptr?
Thanks,
Kuphryn
P.S. auto_ptr declaration cannot be in a switch:
switch (variable)
{
case 1 : auto_ptr<class> temp(new class); // illegal
...
}
-
I think I figure out the essense of auto_ptr. auto_ptr is a quick and easy exception handling for class objects.
Here is a performance question. I always make sure all classes I use are secure from memory leak. I implement exception handling when dealing with many standard library functions that could return errors, i.e. new. Anyways, is it better to use auto_ptr and let the class handles unexpected run-time errors, or is it better to make sure the class is completely error proof (as much as possible)?
Kuphryn
-
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.
-
Okay. Thanks.
auto_ptr is quite simple after I read about it more closely in Stroustrup's book.
I try to construct classes such that there is exception handling at every point where the system could close down the program. Thus, if the program does crash, catch removes all pointers if applicable. The drawback is the there are redundant code, i.e. delete []...delete []...
Kuphryn