Re: returning dynamically allocated object through reference
On Jan 22, 4:52 am, 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;
}
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
You got yourself confused. myVar __will__ be destroyed automatically,
but tempObj will not be destroyed at all, nor will heap allocated for
it be freed. What you did is the following:
1. created an object on the heap
2. returned an unnamed reference to said object (*tempObj in "return
*tempObj")
3. made a copy of *tempObj to create myVar
in more details, this happened:
1. allocate memory
2. construct IntImg in this memory
3. return a reference to above object
4. construct myVar from the above reference using a copy constructor,
IntImg(const IntImg& rhs)
So you are left with myVar, which has automatic (stack) storage and
will be destroyed when it goes out of scope, but you also have another
instance, on the heap, from new ili::IntImg(pImage).
If this helps: for each "new", there has to be a corresponding
"delete" somewhere. You have no delete. And references have absolutely
nothing to do with that.
As for what you are trying to do: you can't return a reference to a
temporary object (because temporary will be destroyed when your
function is finished, so...). You have to return a copy of that.
However, compiler is often able to do what, I think, is called "return
value optimization", and avoid actual copying. So your function really
has to be IntImg synchronize(params), or perhaps IntImg* synchronize
(params), but then, synchronize better create the object on the heap
(as it does) and, once synchronize is done, calling code is the
"owner" of the object and has to delete it eventually.
BTW, as a matter of style, I prefer declaration
Type* pointer_to_object;
to
Type *object;
C-people usually don't like the first one. It's more often seen in C++
code, I think. It looks like C notation may have added to your
confusion.
HTH,
Goran.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]