Another variable is not created when you return, but another memory copy is made from the variable being returned (local variable Input) to the original variable (MyVariable).
As a general rule, for in parameters, you should pass built-in types (int, double, ...) by value and everything else as a const reference. Non-const references should only be used for out or in/out parameters.
As dhayden said, the compiler can often optimise your code. In fact, modern compilers are really quite good at it, and the cases where you need to use by-reference rather than by-value have changed. But the general rule I just mentioned is a good starting point.
In your example, nothing is actually left after it's optimised;
For Visual C++ 2013 compiling:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
using namespace std;
int ReturnAVariable(int Input)
{
return Input;
}
int main()
{
int MyVar = 10;
int RetVar = ReturnAVariable(MyVar);
cout << RetVar;
return 0;
}
|
all that's left, in the optimised build, is;
--- w:\source\explore\cplusplus_vc12\temp_test\main.cpp ------------------------
int MyVar = 10;
int RetVar = ReturnAVariable(MyVar);
cout << RetVar;
011512A0 mov ecx,dword ptr ds:[1153030h]
011512A6 push 0Ah
011512A8 call dword ptr ds:[1153038h]
return 0;
011512AE xor eax,eax
}
011512B0 ret |
Basically, it's loading the literal value (0Ah is hex for 10) on to the stack and then calling cout to display it.
Andy