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?

Room.hpp:

vector<shared_ptr<Item>> items;
void addItem(auto_ptr<Item>);

main:

room.addItem(auto_ptr<Item>(new Item(...)));

Answers


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[1]; // 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:

addItem(auto_ptr<Item>&&);

Keep in mind that the auto_ptr will be empty afterwards.


  1. 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.

  2. Use boost::ptr_vector.


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.


Need Your Help

Does a composable Application necessarily imply a Plugin based architecture

c# .net architecture extensibility

I am currently working on an application and would like to add new functionality to it.

Check if CheckBox is checked, which is not in view of ListView

android

I have ListView, which contains a TextView and a CheckBox.