将std :: auto_ptr作为其成员变量存储在std :: vector中的类的对象是否安全?
我不能在我的项目中使用shared_ptr,没有提升:(
I can't use shared_ptr in my project, no boost :(
所以,我有一个类大致类似下面:
So, I'm having a class roughly similar to the one below:
class MyClass
{
private:
std::auto_ptr<MyOtherClass> obj;
};
现在,我想在std :: vector中存储上面类的实例它安全吗?我在这里阅读在STL容器中使用std :: auto_ptr是错误的。这适用于我的情况吗?
Now, I want to store the instances of above class in std::vector. Is it safe? I've read here that it's wrong to use std::auto_ptr with STL containers. Does it apply to my situation here?
我已将问题作为后续
发布到此答案,请参阅
http://stackoverflow.com/questions/704780/class-containing-autoptr-stored-in-vector 。
假设你的类没有用户定义的拷贝构造函数,然后没有,它可能(见下文)不安全。当你的类被复制(当它被添加到一个向量将发生)auto_ptr的复制构造函数将被使用。这有一个奇怪的行为,传递的东西被复制到副本的所有权,因此被复制的指针的东西现在为null。
Assming your class does not have a user-defined copy constructor, then no, it is probably (see below) not safe. When your class is copied (as will happen when it is added to a vector) the copy constructor of the auto_ptr will be used. This has the weird behaviour of tranferring ownership of the thing being copied to the copy and, so the thing being copied's pointer is now null.
这是可能的,虽然不太可能,你实际上想要这种行为,在这种情况下auto_ptr是安全的。假设您不需要,您应该:
It is possible, though unlikely, that you actually want this behaviour, in which case an auto_ptr is safe. Assuming you do not, you should either:
- 添加复制构造函数以管理复制
请注意,这还不够 - 请参阅上述后续问题了解详情。
或:
- 使用更智能的引用计数指针,例如某个提升智能指针