重新分配“auto_ptr”和管理内存

时间:2009-03-27 16:02:03

标签: c++ memory-management memory-leaks auto-ptr

我的情况是这样的:

class MyClass
{
private:
  std::auto_ptr<MyOtherClass> obj;

public:
  MyClass()
  {
    obj = auto_ptr<MyOtherClass>(new MyOtherClass());
  }

  void reassignMyOtherClass()
  {
    // ... do funny stuff
    MyOtherClass new_other_class = new MyOtherClass();
    // Here, I want to:
    //  1) Delete the pointer object inside 'obj'
    //  2) Re-assign the pointer object of 'obj' to 'new_other_class'
    //     so that 'obj' now manages 'new_other_class' instead of the
    //     object that just got deleted manually
  }
};

有没有办法实现这个目标?以下代码是否符合我的要求?

void MyClass::reassignMyOtherClass()
{
  // ... still, do more funny stuff (flashback humor :-)
  MyOtherClass new_other_class = new MyOtherClass();
  obj.reset(new_other_class);
}

new_other_class的默认析构函数中是否取消分配MyClass的内存?

2 个答案:

答案 0 :(得分:4)

是的,它会。 你可以使用

obj.reset( new MyOtherClass() );

我最好使用这样的构造函数

 MyClass():
     obj( new MyOtherClass() )
 {
 }

答案 1 :(得分:1)

来自描述reset

MSDN
  

成员函数计算表达式delete myptr,但仅当存储的指针值myptr因函数调用而发生变化时才会计算。然后它用ptr。

替换存储的指针

它会做你想要的。