Using auto_ptr :: C++

Status
Not open for further replies.
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
...
}
 
Originally posted by kuphryn:
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?
I don't think that auto_ptr knows about arrays, so it can only be used when single objects are created on the free store.

Personally, I don't do that a whole hell of a lot. Most of the time I need something dynamic-sized; the times I do create a single object, I'm normally creating it on the free store because I *don't* want it to be deallocated automagically. auto_ptr thus isn't particularly useful to me.

P.S. auto_ptr declaration cannot be in a switch:
Yes it can, you need to wrap the block in braces.
 

Bman

Ars Scholae Palatinae
880
I'd snag the smart pointer classes from Boost. From there, my personal guidelines are:

shared_ptr (I think that's the name) for single objects
std::vector for arrays
std::string for strings

I stay away from auto_ptr because Scott Meyers goes into great detail about their flaws in Effective STL. In particular, you should not put auto_ptrs into containers (like vector) because they behave somewhat strangely when you copy them.
 
Okay. Thanks. 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 stand library functions that could return errors, i.e. new. Anyways, is it better to use auto_ptr and let the class handling unexpected run-time errors, or is it better to make sure the class is completely error proof (as much as possibl)?

Kuphryn
 
Status
Not open for further replies.