Returning objects with dynamic memory

Posted by Caulibrot on Stack Overflow See other posts from Stack Overflow or by Caulibrot
Published on 2013-11-04T21:51:06Z Indexed on 2013/11/04 21:53 UTC
Read the original article Hit count: 122

Filed under:

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!

© Stack Overflow or respective owner

Related posts about c++