[英]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
之后将为空。
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.