C ++ lvalue references and rvalue references

The following is a compilation of x86 assembly

Write a simple sentence, to see compilation

int i = 1;
int & ii = i;
0x080483f3  movl   $0x1,-0x10(%ebp)
0x080483fa  lea    -0x10(%ebp),%eax
0x080483fd  mov    %eax,-0x8(%ebp)

The first one is assigned to i 1, i of the second sentence into the address in eax, eax third sentence of the passed value ii. Visible reference is made variable from one address at a variable and then assigned to the reference variable.

Look at compile an rvalue references

int && iii = 10;
0x08048400  mov    $0xa,%eax
0x08048405  mov    %eax,-0xc(%ebp)
0x08048408  lea    -0xc(%ebp),%eax
0x0804840b  mov    %eax,-0x4(%ebp)

The first one will be assigned to 10 eax, eax placed in the second sentence -0xc (% ebp) at said before "temporary variables associated with a reference value to the right, the right to a particular value is stored in location" in this program, -0xc (% ebp) is the address of the temporary variable, by the two eax at the address stored to iii.

By the above code, we also found that, in the above-described procedure -0x4 (% ebp) to store the reference value of the right iii, -0x8 (% ebp) to store the reference value of the left, -0xc (% ebp) the storage 10, and -0x10 (% ebp) kept the 1, left and right reference value reference value, like int is four bytes (because all address)

At the same time, we can understand in depth under temporary variables in this program, with the name of 1 (named i) and no name value 10 (temporary variables) is actually handled by the same way, that is to say, a temporary variable fundamental it is not on a variable name only. Its life cycle and function stack frame is the same. It can be said temporary variable and its reference have the same life cycle.

 

to sum up:

1, left and right values quoted essence no different, are taking address! (Left reference value has its own memory space)

2, the left is to take the value of an existing variable address, you need to create the right value and take temporary storage address. (Rvalue reference has its own memory space)

Published 343 original articles · won praise 57 · Views 200,000 +

Guess you like

Origin blog.csdn.net/jadeshu/article/details/103542579