   Returning a reference to a local? Legal??
  http://www.functionx.com/cpp/examples/returnreference.htm?? I don't understand this... how can you return a reference to a local variable?First of all, this does not even compile for me, unless the return type is a const reference. But even in that case, why is that allowed? Shouldn't the variable being reference already have been destroyed?? (Is it because the number is really a compile-time global constant?)Here is my code sample:const int& foo(){return 5;}int main(){int num = foo(); // compiles ok}
The code on that site is horrendous. I would suggest you stop reading it.Consider this example from the site:double & GetWeeklyHours(){    double h = 46.50;    double &hours = h;    return hours;}They are returning a reference to a non-static stack variable. This is a great way to crash your application.This is basically the same as doing the following (now using pointers):double* GetWeeklyHours(){    double h = 46.50;    return &h;}When the function returns, the stack will unwind, and the pointer that is returned is pointing at invalid memory.Luckily your compiler prevented you from reproducing the mistakes on that site.const int& foo(){return 5;}int main(){int num = foo(); // compiles ok}In the code you wrote, the number '5' is a constant that is stored in the data segment of your executable, thus the reference that you return must be a constant reference to int.[Edited by - fpsgamer on August 26, 2007 2:21:15 AM];  The number returned is specified as a literal and hence it's not really a local variable but a constant. Since these are not allocated on the stack, returning const pointers to them is "okay". However, the only reason why you would return an int by reference is, because you want be able to change the value and also modify whichever global or member variable it references.   ;  Ok... well, that was a simple example I found via googling. Thatnks for clearing that up. But my original question arose from this article:http://www.jaggersoft.com/pubs/oload30.htmlHere's the snippet, down under the Reference or Value? heading:Quote:... Consider const char & example(){    const string greeting("Hello");    return greeting[0];}If the const subscript operator returns a char reference then example will return a dangling const reference to the initial char of greeting which will go out of scope when example returns. Oops. However, if the const subscript operator returns a value char string::operator[](size_t index) const;then example() will return a const reference to a copy of the initial char of greeting, and all is well...How does that work? Can you return a const reference to a value like that?EDIT: OH -- is this the reason? ==> This would be a problem as well, EXCEPT the string is a const string and thus a literal and thus it goes in the data segment too.   ;Quote:Original post by discman1028EDIT: OH -- is this the reason? ==> This would be a problem as well, EXCEPT the string is a const string and thus a literal and thus it goes in the data segment too.No.A literal is always an unnamed programmer-provided value of a base type. So "Hello" is a string literal (which is probably moved to the data segment) while greeting is a constant std::string but not a literal (it's not unnamed, it's not a value, it's not programmer-provided, and it's not a base type).When constructing a const variable of a non-basic type, the compiler may lack the information necessary to determine whether the constructor has a side-effect or not, and thus may be forced to keep the variable out of the data segment and initialize it every time the function is called. This is compiler- and library-dependent.The variable greeting is an auto variable—data segment or not, the standard forbids you from referencing it, or any data it owns, after the scope it was in is left. And, of course, the character reference will (if any) reference the internal copy greeeting has made from the literal, which is owned by it and thus will be gone.And, regardless of all this, the text you quoted is wrong: a return value is a temporary, and will be gone by the time the function returns, so no referencing is possible here.   ;Quote:Original post by ToohrVykAnd, regardless of all this, the text you quoted is wrongRandom C++ pages on the internet are 0 for 2 in terms of having correct information so far.I'd recommend the you get a solid (as in the pulp and paper variety) C++ book to learn from instead. Granted those can have errors to, but they also have reviews and recommendations of them available from trust worthy sources.   ;Quote:Original post by ToohrVykA literal is always an unnamed programmer-provided value of a base type. So "Hello" is a string literal (which is probably moved to the data segment) while greeting is a constant std::string but not a literal (it's not unnamed, it's not a value, it's not programmer-provided, and it's not a base type).When constructing a const variable of a non-basic type, the compiler may lack the information necessary to determine whether the constructor has a side-effect or not, and thus may be forced to keep the variable out of the data segment and initialize it every time the function is called. This is compiler- and library-dependent.The variable greeting is an auto variable—data segment or not, the standard forbids you from referencing it, or any data it owns, after the scope it was in is left. And, of course, the character reference will (if any) reference the internal copy greeeting has made from the literal, which is owned by it and thus will be gone.About the 2nd bullet, I wasn't sure if maybe if the constructor was simple enough, the compiler could decide to put the object in the data segment. I was thinking that maybe that was the article writer's assumptions...Quote:Original post by ToohrVykAnd, regardless of all this, the text you quoted is wrong: a return value is a temporary, and will be gone by the time the function returns, so no referencing is possible here.That's what I had hoped... the following sentence seemed so wrong to me. Now I am at peace. ;)Quote:...then example() will return a const reference to a (temp!) copy of the initial char of greeting, and all is well...;Quote:Original post by fpsgamerThe code on that site is horrendous. I would suggest you stop reading it.Oh good gawd you're right - Every example I looked at is terrible!   ;  As others have said the code on that site is horrible, if you really don't want to but a book then there are a number of good C++ books with free copies available on line, for example Thinking in C++;  Lets not forget this little corner case.int foo() { return someint; }int main() {   int& bar = foo();}The reference 'bar' refers to a return value, so you'd think it would become an invalid reference. But it doesn't! The compiler keeps it around anyway, just so this code can be legal.   