I have read this article:
Http://blog.csdn.net/newslxw/archive/2006/08/08/1038972.aspx
I still remember when I was studying, Niu's c ++ teacher told me: "reference is actually an alias, which is exactly the same as the referenced object ". however, I still have this question: "What is equivalent? Does it mean that the two are directly using the same memory location in the underlying implementation? "For example, the following code:
Int main ()
...{
Int A = 100;
Int & B =;
Int * c = &;
B = 99;
A = 88;
B = 77;
* C = 66;
Return 0;
}
After compilation, it becomes like this:
Main:
Leal 4 (% ESP), % ECx
Andl $-16, % ESP
Pushl-4 (% ECx)
Pushl % EBP
Movl % ESP, % EBP
Pushl % ECx
Subl $16, % ESP
. Lcfi5:
Movl $100,-16 (% EBP); ebp-16 is the address of variable
Leal-16 (% EBP), % eax
Movl % eax,-12 (% EBP); place the address of a at the ebp-12 address
Leal-16 (% EBP), % eax
Movl % eax,-8 (% EBP); The ebp-8 is the pointer C variable, this sentence is to assign a value to the pointer C
Movl-12 (% EBP), % eax; before assigning a value to reference B, take the address of a with a ebp-12 to eax
Movl $99, (% eax); B = 99
Movl $88,-16 (% EBP)
Movl-12 (% EBP), % eax; here, we assign a value to reference B, which is the same as the previous one.
Movl $77, (% eax)
Movl-8 (% EBP), % eax; obtain the C address before assigning values to * C.
Movl $66, (% eax); run * c = 66 here
Movl $0, % eax
Addl $16, % ESP
Popl % ECx
Popl % EBP
Leal-4 (% ECx), % ESP
RET
It can be seen that, in actual implementation, a temporary space (stack space) will be applied for to store the address of the referenced object. when a referenced variable is used, the referenced object is indirectly addressable. from the perspective of assembly code, * C is indeed the same as B's assembly code in use. It takes the address first and then saves the value to this address. the difference is that at the C ++ level, as a reference type variable such as B, values can only be assigned at initialization and can only be assigned once.