storing pointers to auto_ptr in vector

1.1k Views Asked by At

Can one store pointers to auto_ptr(s) in a std::vector? Is it safe?

I enumerate a folder reading in XML files and creating an object for each with auto_ptr. I don't know in advance how many XML files there will be and I'd like to use a vector to essentially keep a list of pointers to them.

I'm also assuming that when a pointers are removed from the Vector (or the vector is destroyed) the pointers are pretty much gone, so I wouldn't have to worry about setting them to NULL.

2

There are 2 best solutions below

3
On

Yes you could - but it is totally unsafe and will do all sorts of unexpected things that will surprise you.

If you want to store smart pointers in a container have a look at unique_ptr if your compiler supports C++11 stuff

0
On

You can't store an auto_ptr itself in a std::vector, but storing a plain pointer is fine, even if the thing it points to is an auto_ptr.

I don't see why you'd want to do that, though. The whole point of auto_ptr is to ensure that heap-allocated objects are deleted automatically when they go out of scope. You lose that benefit if the auto_ptr itself has to be deleted manually.

If you want to store heap-allocated objects safely in a vector, you can use std::tr1::shared_ptr instead of auto_ptr, or use Boost's pointer containers. Or, if you're using C++11, std::unique_ptr is like std::auto_ptr except it's safe to use in containers.