Re: Life time of an object and Reference Var
maverick wrote:
Pls consider the following code:
class Foo
{
};
Foo& getFoo ( void )
{
Foo obj;
}
int main ( void )
{
Foo &ref = g();
}
My question is if the obj will be live untill ref? because
reference variables must be initialised when declared and g()
cannot return a 'dead' object.
You don't define a g(), so it's difficult to tell. I suspect
that you meant to use getFoo to initialize ref. In which
case... you don't have a return statement in getFoo, so you have
undefined behavior, because you fall off the end of a non void
function. If we suppose in addition that you meant for getFoo
to end with "return obj", then you are returning a reference to
a local object, which will be destructed as soon as you leave
the function.
Is a logical bug as not to return reference of local object or
no problem at all.
It's a very serious logical error; in simple cases like this,
most compilers will generate a warning, but there are more
complicated cases which the compiler cannot detect.
--
James Kanze kanze.james@neuf.fr
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]