C++ - Putting auto_ptrs in a shared_ptr vector
I have a vector of shared_ptrs. I'm currently putting auto_ptrs into it. Is that okay or will things break?
vector<shared_ptr<Item>> items; void addItem(auto_ptr<Item>);
Don't. auto_ptr has been deprecated in C++11 and criticized since its inception because of its strange ownership semantics. Copying an auto_ptr will transfer ownership to the copied object. In your case that might be alright, but if you do, for example:
auto_ptr<Item> x = room; // ouch
things start to get ugly.
Use a std::shared_ptr if you require shared ownership or a std::unique_ptr if you don't. If you don't have a C++11 compiler, use Boost.SmartPointers. There is also a Boost.Pointer Container if you only use pointers for polymorphism instead of shared ownership.
If you really want to keep your API that way, you need to use:
Keep in mind that the auto_ptr will be empty afterwards.
Don't use auto_ptr in any STL containers. And don't use auto_ptr at all! There is good article about auto_ptr's troubles on gotw: GotW#25.
That will work - shared_ptr has a constructor that transfers ownership from an auto_ptr.
However, auto_ptr is best avoided due to its strange destructive-copy semantics; in C++11, unique_ptr should be preferred for single transferable ownership. That can also be used to initialise a shared_ptr.