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.
It’s fairly obvious that you want to return a new object to the caller that you do not need to keep any reference to. For this purpose, the simplest thing to do is to return the object by value.
Then in the calling code you can construct the new object like this.
This avoids any worries about returning reference to temporaries or requiring the client to manager deletion of a returned pointer. Note, that this does require your object to be copyable, but it is a legal and commonly implemented optimization for the copy to be avoided when returning by value.
You would only need to consider a shared pointer or similar if you need shared ownership or for the object to have a lifetime outside the scope of the calling function. In this latter case you can leave this decision up to the client and still return by value.
E.g.