views:

99

answers:

2

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?

+4  A: 

Yes it will. You can use

obj.reset( new MyOtherClass() );

And I'd better use such constructor

 MyClass():
     obj( new MyOtherClass() )
 {
 }
Mykola Golubyev
Mykola, thank you! I'm so used to Java that I find the constructor initialization list repulsive, as if I don't trust that it assigns the right values :) A question though: can we use initialization list even if the object disallows copy construction? May be this is why I don't trust this :)
artknish
It doesn't use copy constructor. It uses constructor.
Mykola Golubyev
+1  A: 

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.

Andrew Stein