Re: returning dynamically allocated object through reference
mundacho@gmail.com wrote:
I'd like to know if this code is going to create a memory leak in the
calling function:
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
It is not likely to be, you however have to deference the pointer.
The only advantage would be to ensure that your function won't return
NULL (and errors are handled by exceptions).
because the object
is not copied but passed directly, isn't it?
Yes.
A pointer is also directly passed.
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???
No.
You have a memory leak here unless your constructor manages the lifetime
of its parameter.
And no gain in performance, you still have a copy.
You can do:
li::IntImg& myVar = synchronize(image);
But latter on, you would have to call:
delete &myVar;
--
Michael