Re: returning dynamically allocated object through reference
On Jan 22, 6:52 am, munda...@gmail.com wrote:
I'd like to know if this code is going to create a memory leak in the
calling function (this codes compiles):
It does : your program behaves like a worm(virus that ueses up ram
and slows down the computer).
ili::IntImg
&RectangleImageComparator::synchronize(const ili::IntImg &pImage)
use a pointer instead:
ili::IntImg* //mind the asterisk(pointer declarator)
RectangleImageComparator::synchronize(const ili::IntImg &pImage)
{
ili::IntImg *tempObj = new ili::IntImg(pImage);
return *tempObj;
return tempObj;//ommit the asterisk
}
i wanted to return a reference because it's faster because the object
is not copied but passed directly, isn't it?.
It is ,but not the way you are doing.
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);
I might write:
ili::IntImg* myVar = synchronize(image);
// will myVar be destroyed
automatically???
No ,and that is exactly why your program is a worm.
you have to explicitly discard the dynamically allocated (allocated
via "new") memmory:
delete myVar;
you can also make use some smart pointetr library:
std::auto_ptr <My_data> foo(){
std::auto_ptr <My_data> var= new My_data(initializers);
........//rest of algorythm
return var;
};
std::auto_ptr <My_data> myptr=foo();
in this cas you wont need to deallocate the object.
Regards,
FM.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]