Re: returning dynamically allocated object through reference
mundacho@gmail.com wrote:
hello,
I'd like to know if this code is going to create a memory leak in the
calling function (this codes compiles):
ili::IntImg
&RectangleImageComparator::synchronize(const ili::IntImg &pImage)
{
ili::IntImg *tempObj = new ili::IntImg(pImage);
return *tempObj;
}
i wanted to return a reference because it's faster because the object
is not copied but passed directly, isn't it?. My question is if the
calling function will free automatically the object returned, if I do:
// in the calling function I'd do:
ili::IntImg myVar = synchronize(image); // will myVar be destroyed
automatically???
Thanks in advance,
eD
The function *by itself* will not cause the memory leak, although it is
more usual to return a new'ed object by pointer. If the caller assumes
ownership of the object and knows that it must call delete on the
address of the object at some point, it should work. The object new'ed
does not go out of scope at the end of the function; only the memory
occupied by the pointer goes away.
However, the way you are CALLING it will certainly cause a memory leak!
This is because you are creating TWO objects: one inside synchronize()
with new, and the other on the stack inside the calling function. Since
you have a different object here, you will never be able to retrieve the
address of the first object in order to delete it.
What you want to do is one of the following:
(1) Return the new object by pointer instead of by reference. This makes
it easier for whoever is reading your code to realize that the object
was created with new. Document the fact that the caller must assume
ownership of the object.
- or -
(2) Call the function like this:
ili::IntImg &myVar = synchronize(image);
(Note that ili::myVar is now a reference and not an object). You will
have to delete it like this:
delete &ili::myVar;
In either case, you should check the pointer returned from new inside
synchronize() for NULL or catch any exception which might be thrown by
the constructor of your image object.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]