return reference to local variable, good code?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • George2
    New Member
    • Dec 2007
    • 200

    #1

    return reference to local variable, good code?

    Hello everyone,


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

    Code:
    class Foo {
    
    };
    
    Foo& func()
    {
    	Foo foo;
    	return foo;
    }
    
    int main()
    {
    	Foo& foo = func();
    
    	return 0;
    }
    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
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    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

    Comment

    • George2
      New Member
      • Dec 2007
      • 200

      #3
      Thanks for your advice, Jos!


      My question is answered.

      Originally posted by JosAH
      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

      Comment

      Working...