I can’t use shared_ptr in my project, no boost 🙁
So, I’m having a class roughly similar to the one below:
class MyClass { private: std::auto_ptr<MyOtherClass> obj; };
Now, I want to store the instances of above class in std::vector. Is it safe? I’ve read here that it’s wrong to use std::auto_ptr with STL containers. Does it apply to my situation here?
Assming your class does not have a user-defined copy constructor, then no, it is probably (see below) not safe. When your class is copied (as will happen when it is added to a vector) the copy constructor of the auto_ptr will be used. This has the weird behaviour of tranferring ownership of the thing being copied to the copy and, so the thing being copied’s pointer is now null.
It is possible, though unlikely, that you actually want this behaviour, in which case an auto_ptr is safe. Assuming you do not, you should either:
Note this is not enough – see the follow-up question mentioned above for more info.
or: