C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Life time of an object and Reference Var

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated)
View previous topic :: View next topic  
Author Message
maverick
Guest





PostPosted: Sat May 06, 2006 5:21 pm    Post subject: Life time of an object and Reference Var Reply with quote



Hi,

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. Is a logical bug as not to return reference of local
object or no problem at all.

Thanks


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
James Kanze
Guest





PostPosted: Sun May 07, 2006 1:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote



maverick wrote:

Quote:
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.

Quote:
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 (AT) neuf (DOT) 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! ]
Back to top
James Dennett
Guest





PostPosted: Sun May 07, 2006 1:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote



maverick wrote:
Quote:
Hi,

Pls consider the following code:

class Foo
{
};

Foo& getFoo ( void )
{
Foo obj;

assuming you meant to add
return obj; // NOTE: BUG
as the last line of this function.

Quote:
}

int main ( void )

(Style note: most C++ "natives" don't use the C-style of
writing void to denote an empty argument list: int main()
means the same thing in C++. I have, however, seen house
styles which require the explicit "void" marker.)

Quote:
{
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. Is a logical bug as not to return reference of local
object or no problem at all.

Returning a reference to a local variable is a bug.
The object will be destroyed when the function exits
(or leaves the scope of that local variable), and
so you have a dangling reference.

-- James

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
\"@velu\".invalid
Guest





PostPosted: Mon May 08, 2006 8:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote

Hi james,

Assume the following case

class Foo
{
};


Foo& getFoo ( void )
{
Foo* objptr = new Foo;
return objptr;
} ;

int main ( void )
{
Foo &ref = getFoo( );
}

will this code work ?

Thanks,
~velu


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
\"@velu\".invalid
Guest





PostPosted: Mon May 08, 2006 8:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote

Hi james,

Assume the following case

class Foo
{
};


Foo& getFoo ( void )
{
Foo* objptr = new Foo;
return objptr;
} ;

int main ( void )
{
Foo &ref = getFoo( );
}

will this code work ?

Thanks,
~velu


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
maverick
Guest





PostPosted: Mon May 08, 2006 8:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote

James,

Sorry for not defining g(). But let me do it as follows:

foo& g()
{
foo local;
return local;
}

and lets also add a member var to class Foo say i of int type--
class Foo
{

int i;
Foo ( int j = 0 ) : i(j){}

};

now let say,
int main()
{

Foo& ref = g();
ref.i = 10; //?????CORE???
}

but it never core dumps.

Thanks


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
James Kanze
Guest





PostPosted: Tue May 09, 2006 12:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote

maverick wrote:

Quote:
Sorry for not defining g(). But let me do it as follows:

foo& g()
{
foo local;
return local;
}

As has already been pointed out, this will result in undefined
behavior as soon as you use the reference you return. Most
compilers will warn you.

Quote:
and lets also add a member var to class Foo say i of int type--
class Foo
{

int i;
Foo ( int j = 0 ) : i(j){}

};

now let say,
int main()
{
Foo& ref = g();
ref.i = 10; //?????CORE???
}

but it never core dumps.

So. It's undefined behavior. Anything can happen. It might
even seem to work.

--
James Kanze kanze.james (AT) neuf (DOT) 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! ]
Back to top
loufoque
Guest





PostPosted: Tue May 09, 2006 1:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote

"@velu".invalid wrote :

Quote:
class Foo
{
};


Foo& getFoo ( void )
{
Foo* objptr = new Foo;
return objptr;
} ;

int main ( void )
{
Foo &ref = getFoo( );
}

will this code work ?

No.
You need return *objptr;

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
Tomás
Guest





PostPosted: Tue May 09, 2006 1:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote

Quote:
class Foo
{
};


Foo& getFoo ( void )
{
Foo* objptr = new Foo;
return objptr;
} ;

int main ( void )
{
Foo &ref = getFoo( );
}

will this code work ?


No, but only because you made typos. I'll rewrite it, and I'll use
"std::string":

#include <string>
using std::string;

string& FuncReturnRef()
{
string *p_str = new string;

return *p_str; /* You forgot to dereference in your previous code */
}


int main()
{
string &str = FuncReturnRef();

/* Can't forget to delete */

delete &str;
}


Here's another sample for your perusal:

#include <string>
using std::string;

string FuncReturnByValue()
{
return "Hello!";

/* Or, if you'd prefer:

return string("Hello!");

*/
}

#include <iostream>
using std::cout;

int main()
{
const string &str = FuncReturnByValue();

/* By binding the return value of a function which
returns-by-value to a const reference, we have
extended the lifetime of the temporary object. */

cout << str;
}


-Tomás

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
red floyd
Guest





PostPosted: Tue May 09, 2006 1:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote

"@velu".invalid wrote:
Quote:
Hi james,

Assume the following case

class Foo
{
};


Foo& getFoo ( void )
{
Foo* objptr = new Foo;
return objptr;
} ;

int main ( void )
{
Foo &ref = getFoo( );
}

will this code work ?



No, because objptr is a Foo*, not a Foo&.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
James Kanze
Guest





PostPosted: Tue May 09, 2006 1:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote

"@velu".invalid wrote:

Quote:
Assume the following case

class Foo
{
};

Foo& getFoo ( void )
{
Foo* objptr = new Foo;
return objptr;
} ;

int main ( void )
{
Foo &ref = getFoo( );
}

will this code work ?

Have you tried compiling it? C++ has a type system, and while
there are far too many implicit conversions for my tastes, there
are limits. A pointer is not the same thing as the object
pointed to.

--
James Kanze kanze.james (AT) neuf (DOT) 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! ]
Back to top
Gerhard Menzl
Guest





PostPosted: Tue May 09, 2006 8:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote

"@velu".invalid wrote:

Quote:
class Foo
{
};


Foo& getFoo ( void )
{
Foo* objptr = new Foo;
return objptr;
} ;

int main ( void )
{
Foo &ref = getFoo( );
}

will this code work ?

It won't even compile. You are trying to return a Foo* from a function
that returns a Foo&.

If you correct this to

Foo& getFoo ()
{
Foo* objptr = new Foo;
return *objptr;
}

the code will work, but it is very bad practice. Who is responsible for
deleting the dynamically allocated Foo object? Returning a reference
does not signal a transfer of ownership. It is also not exception-safe.
The standard, exception-safe way of doing it would be something like:

#include <memory>

class Foo {};

typedef std::auto_ptr<Foo> FooPtr;

FooPtr getFoo ()
{
return FooPtr (new Foo);
}

int main ()
{
FooPtr foo (getFoo () );
// main now owns foo and uses it
// ...
// foo will be automatically deleted here, even when
// an exception is thrown before
}

--
Gerhard Menzl

#dogma int main ()

Humans may reply by replacing the thermal post part of my e-mail address
with "kapsch" and the top level domain part with "net".

The information contained in this e-mail message is privileged and
confidential and is for the exclusive use of the addressee. The person
who receives this message and who is not the addressee, one of his
employees or an agent entitled to hand it over to the addressee, is
informed that he may not use, disclose or reproduce the contents thereof.


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
Gerhard Menzl
Guest





PostPosted: Tue May 09, 2006 8:21 pm    Post subject: Re: Life time of an object and Reference Var Reply with quote

maverick wrote:

Quote:
Sorry for not defining g(). But let me do it as follows:

foo& g()
{
foo local;
return local;
}

and lets also add a member var to class Foo say i of int type--
class Foo
{

int i;
Foo ( int j = 0 ) : i(j){}

};

now let say,
int main()
{

Foo& ref = g();
ref.i = 10; //?????CORE???
}

but it never core dumps.

The fact that a program doesn't core dump when you run it does not prove
that it is correct. Your program accesses an object that does not exist
anymore and exhibits undefined behaviour. Undefined behaviour can mean
anything, including that it seems to be working. You apparently get away
with it because you have a toy program that doesn't do anything besides
creating and destroying a single automatic object. But if you do
something like this in a non-trivial program, you are likely to cause
totally unpredictable effects that can be very hard to track down.

--
Gerhard Menzl

#dogma int main ()

Humans may reply by replacing the thermal post part of my e-mail address
with "kapsch" and the top level domain part with "net".

The information contained in this e-mail message is privileged and
confidential and is for the exclusive use of the addressee. The person
who receives this message and who is not the addressee, one of his
employees or an agent entitled to hand it over to the addressee, is
informed that he may not use, disclose or reproduce the contents thereof.


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated) All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.