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?
Yes it will. You can use
And I’d better use such constructor