Returning objects with dynamic memory
- by Caulibrot
I'm having trouble figuring out a way to return an object (declared locally within the function) which has dynamic memory attached to it. The problem is the destructor, which runs and deletes the dynamic memory when the object goes out of scope, i.e. when I return it and want to use the data in the memory that has been deleted! I'm doing this for an overloaded addition operator.
I'm trying to do something like:
MyObj operator+( const MyObj& x, const MyObj& y )
{
MyObj z;
// code to add x and y and store in dynamic memory of z
return z;
}
My destructor is simply:
MyObj::~MyObj()
{ delete [] ptr; }
Any suggestions would be much appreciated!