Srikanth
Srikanth

Reputation: 12120

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?

Upvotes: 1

Views: 292

Answers (2)

Andrew Stein
Andrew Stein

Reputation: 13190

From MSDN where describing reset

The member function evaluates the expression delete myptr, but only if the stored pointer value myptr changes as a result of function call. It then replaces the stored pointer with ptr.

It will do what you want.

Upvotes: 1

Mykola Golubyev
Mykola Golubyev

Reputation: 59932

Yes it will. You can use

obj.reset( new MyOtherClass() );

And I'd better use such constructor

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

Upvotes: 4

Related Questions