471,092 Members | 1,009 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,092 software developers and data experts.

return reference to local variable, good code?

200 100+
Hello everyone,


I am reading some code from other people, there are some code like this,

Expand|Select|Wrap|Line Numbers
  1. class Foo {
  2.  
  3. };
  4.  
  5. Foo& func()
  6. {
  7.     Foo foo;
  8.     return foo;
  9. }
  10.  
  11. int main()
  12. {
  13.     Foo& foo = func();
  14.  
  15.     return 0;
  16. }
  17.  
I want to confirm with you that it is not good code, since we return a reference to local object instance, right? Even if the code has expected function currently.


thanks in advance,
George
Dec 16 '07 #1
2 966
JosAH
11,448 Expert 8TB
That code is as wrong as it can be: variable 'foo' doesn't exist anymore after the
function has returned, so the reference points somewhere into la-la-land.

kind regards,

Jos
Dec 16 '07 #2
George2
200 100+
Thanks for your advice, Jos!


My question is answered.

That code is as wrong as it can be: variable 'foo' doesn't exist anymore after the
function has returned, so the reference points somewhere into la-la-land.

kind regards,

Jos

regards,
George
Dec 17 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by Kench | last post: by
25 posts views Thread by cppaddict | last post: by
14 posts views Thread by Gama Franco | last post: by
23 posts views Thread by Nascimento | last post: by
4 posts views Thread by | last post: by
7 posts views Thread by George2 | last post: by
2 posts views Thread by zheng4t | last post: by
275 posts views Thread by Astley Le Jasper | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.