I have a C++ memory management doubt, that's (obviously) related to references and pointers. Suppose I have a class Class
with a method my_method
:
OtherClass& Class::my_method( ... ) {
OtherClass* other_object = new OtherClass( ... );
return *other_object;
}
Meanwhile in a nearby piece of code:
{
Class m( ... );
OtherClass n;
n = m.my_method( ... );
}
So, I know that there's a general rule about pointers (~ "anything new-ed, must be delete-d") to avoid memory leaks. But basicly I'm taking a reference to my heap-allocated object, so when n goes out of scope, shouldn't the destructor of OtherClass be called thus freeing the memory previously pointed by other_object? So in the end the real question is: will this lead to a memory leak?
Thanks.
Yes that will lead to a memory leak.
What you'll do is, in the return statement, dereference the new object you created. The compiler will invoke the assignment operator as part of the returning and copy the CONTENTS of your new object to the object it's assigned to in the calling method.
The new object will be left on the heap, and its pointer cleared from the stack, thus creating a memory leak.
Why not return a pointer and manage it that way?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With