简体   繁体   中英

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(...)));

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM