Search code examples
c++memory-managementmemory-leaksauto-ptr

Re-assinging an "auto_ptr" and Managing Memory


I've a situation like this:

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
  }
};

Is there a way to achieve this? Will the following code do what I want?

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

Will the memory of new_other_class be de-allocated in the default destructor of MyClass?


Solution

  • Yes it will. You can use

    obj.reset( new MyOtherClass() );
    

    And I'd better use such constructor

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