I want to know how the compiler save this temporary int if I call the function f(3);
int f (int x) { return x; }
and how this will be excuted by the compiler :
int a=f(3);
is it just like doing int a=x; (I know x will be already destroyed ) or it really create a temporary variable called f(3), like this int f(3)=x;
int& a=f(3);
and why this wont work ?
Function calls
The compiler will do one of the following things:
int a = 3.Reference variables in C++
A reference variable, one declared as
int &ain your code is “a different name for an existing memory location”. So declaringint &adoes not allocate space for anintanywhere. It just declaresato refer to an already allocated memory location.This location may be an existing variable
int b, so that you say:Here,
awill refer to the same contents thatbrefers to. “A new name for an existing object” is a good idiom to go with.You could get fancy and say
int &a = array[5], so thatarefers to 6th element of anintarrayarray, orint &a = *(int*)0x12345678to refer to a specific memory location, but I’m digressing.Your code
cannot work, because
3is a temporary object, which will be forgotten after the statement is executed. To understand the problem more fundamentally think of this: Ifarefers to an already allocated memory location, what will it refer to, after the statementint &a = 3is executed, and there is no longer a temporary object3?This is also a common problem with reference variables in functions: returning a reference to a function-local object is undefined behavior… but I’m digressing again. You always have to have a “living, allocated object” for
ato refer to, end of story.A bit more in-depth on reference variables
What typically happens for a statement like
is that the compiler generates code to (simplified):
The point is: in either case, there is no long-lived memory location allocated for the object
3, so anint &areally cannot be made to refer to this object because of that.“long-lived memory location” means a location that will live past the assignment operation. The register where 3 is stored will be overwritten and reused probably immediately after the assignment operation, so it doesn’t qualify even theoretically for the target of
int &a(in practice,int &acan only be made to refer to a memory location, not a register, anyway).