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;
}
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???
{ Edits: quoted sig & banner removed. -mod }
Hi,
First of all i think you shouldn't try to speed up your application by
assuming that call / return by reference is generally faster than by
value. You'd rather trust in the capabilities of your compiler in
optimizing. If you still think your program has some bottlenecks use a
profiling tool to find them.
However:
With your approach you get a memory leak. Yes.
It's generally no good idea to allocate melmory within a function and
return it via a reference. Here you'd better return a pointer to that
memory. So the caller of the function can see that this pointer
probably needs a delete or something like that.
If i wanted to use your function and only saw the declaration i would
never-ever think that the returned reference was created with new and
needed a delete.
Another nice possibillity to avoid a memory leak here would be to
return a auto_ptr<ili::IntImg>. The auto_ptr is a wrapper around the
pointer and would delete the pointer when it's scope is left. And it
transfers the ownership in case of copying or assignment.
So you could write:
auto_ptr<ili::IntImg> myVar = synchronize(image);
// when myVar goes out of scope the pointer will be deleted.
greetings,
robert
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]