在std :: vector中存储具有std :: auto_ptr作为其成员变量的类的对象是否安全?

Sri*_*nth 3 c++ memory-management stl

我不能在我的项目中使用shared_ptr,没有提升:(

所以,我的课程大致类似于下面的课程:

class MyClass
{
private:
  std::auto_ptr<MyOtherClass> obj;
};
Run Code Online (Sandbox Code Playgroud)

现在,我想在std :: vector中存储上面类的实例.安全吗?我在这里读到 std :: auto_ptr与STL容器一起使用是错误的.这适用于我的情况吗?

bay*_*yda 6

这是不安全的,因为容器将复制MyClass instnace默认复制操作符将调用所有成员的副本 - 以及auto_ptr成员也是如此,我们将遇到您在问题中描述的相同情况(将auto_ptr存储在容器中)

顺便说一句:为了避免在编译时混淆添加

private:
  MyClass& operator=( const MyClass& );  
  MyClass( const MyClass& );
Run Code Online (Sandbox Code Playgroud)

编译器输出错误,如果您将尝试使用复制操作符,这可以节省您的调试时间.