简体   繁体   English

C ++-将auto_ptrs放在shared_ptr向量中

[英]C++ - Putting auto_ptrs in a shared_ptr vector

I have a vector of shared_ptrs. 我有一个shared_ptrs的向量。 I'm currently putting auto_ptrs into it. 我目前正在将auto_ptrs放入其中。 Is that okay or will things break? 这样可以吗?

Room.hpp: 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. 自从C ++ 11起, auto_ptr就已弃用,并且由于其奇怪的所有权语义而受到批评。 Copying an auto_ptr will transfer ownership to the copied object. 复制auto_ptr会将所有权转移到复制的对象。 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. 如果您需要共享所有权,请使用std::shared_ptr如果不需要,请使用std::unique_ptr If you don't have a C++11 compiler, use Boost.SmartPointers. 如果没有C ++ 11编译器,请使用Boost.SmartPointers。 There is also a Boost.Pointer Container if you only use pointers for polymorphism instead of shared ownership. 如果仅将指针用于多态而不是共享所有权,则还会有一个Boost.Pointer容器

If you really want to keep your API that way, you need to use: 如果您真的想保留您的API,则需要使用:

addItem(auto_ptr<Item>&&);

Keep in mind that the auto_ptr will be empty afterwards. 请记住, auto_ptr之后将为空。

  1. Don't use auto_ptr in any STL containers. 不要在任何STL容器中使用auto_ptr And don't use auto_ptr at all! 而且根本不要使用auto_ptr There is good article about auto_ptr 's troubles on gotw : GotW#25 . 关于gotw的 auto_ptr的麻烦,有一篇很好的文章: GotW#25

  2. Use boost::ptr_vector . 使用boost::ptr_vector

That will work - shared_ptr has a constructor that transfers ownership from an auto_ptr . 这将起作用shared_ptr具有一个构造函数,该构造函数从auto_ptr转移所有权。

However, auto_ptr is best avoided due to its strange destructive-copy semantics; 但是,由于auto_ptr具有奇怪的破坏性复制语义,因此最好避免使用。 in C++11, unique_ptr should be preferred for single transferable ownership. 在C ++ 11中,唯一可转让所有权应首选unique_ptr That can also be used to initialise a shared_ptr . 这也可以用来初始化shared_ptr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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