Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a reference to a local or temporary variable [duplicate]

Tags:

c++

Look at the code below. I know it doesn't return the address of local variable, but why does it still work and assign the variable i in main() to '6'? How does it only return the value if the variable was removed from stack memory?

#include <iostream>  int& foo() {     int i = 6;     std::cout << &i << std::endl; //Prints the address of i before return     return i; }  int main() {     int i = foo();     std::cout << i << std::endl; //Prints the value     std::cout << &i << std::endl; //Prints the address of i after return } 
like image 860
cpx Avatar asked Apr 30 '10 11:04

cpx


People also ask

Can we return a local variable by reference?

Objects returned by reference must live beyond the scope of the function returning the reference, or a dangling reference will result. Never return a local variable by reference.

Is it good idea to return an address or a reference of a local variable?

The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.

Can we return reference of local variable in C++?

Returning values by reference in C++ A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var.

How the returning by reference is performed?

Example: Return by Reference In program above, the return type of function test() is int& . Hence, this function returns a reference of the variable num . The return statement is return num; . Unlike return by value, this statement doesn't return value of num , instead it returns the variable itself (address).


1 Answers

You got lucky. Returning from the function doesn't immediately wipe the stack frame you just exited.

BTW, how did you confirm that you got a 6 back? The expression std::cout << &i ... prints the address of i, not its value.

like image 158
Marcelo Cantos Avatar answered Oct 01 '22 08:10

Marcelo Cantos