Re: returning dynamically allocated object through reference
On 22 jan, 04:52, munda...@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;
}
Yes, of course.
Who would free it here?
I recommend you read about the basics of C++ programming, mainly RAII
and ownership of resources.
Someone must own the resource and be responsible for freeing it.
Here, you should just write
ili::IntImg RectangleImageComparator::synchronize(const ili::IntImg
&pImage)
{
return ili::IntImg(pImage); // or return pImage; ?
}
(I have to admit, however, I don't really see the point of that
function, it only returns a copy of its argument).
i wanted to return a reference because it's faster because the object
is not copied but passed directly, isn't it?.
No.
It's just different. A reference is a reference. Here you want to
return a new object, not a reference to one that already exists and is
owned by someone else.
Returning by value is actually more efficient if the result is used
for construction.
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???
myVar, which is a copy of the reference you returned, will be
destroyed automatically, yes.
However it won't free the reference.
Now if you write that with the code I provided, then yes, it becomes
correct.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]