Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will this lead to a memory leak in C++?

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.

like image 965
tunnuz Avatar asked Jan 24 '09 11:01

tunnuz


1 Answers

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?

like image 65
Adam Hawes Avatar answered Sep 27 '22 22:09

Adam Hawes