About the use of reference pointers

xiaoxiao2021-03-06  60

Today, there are friends asking me a question about the reference pointer:

Const int a = 4;

Const Int * Pi = & A;

Const int * & ri = pi; // ok const INT * & ri = & a Error

He said why const Int * & ri = & a will have an error, but const Int * & ri = Pi can be compiled. Ri is not a pointer, why can't it receive the address of the A variable?

In fact, we can know the reason as long as we disconnect the above code.

4: Const Int * Pi = & A;

0040102f Lea Eax, [EBP-4]

00401032 MOV DWORD PTR [EBP-8], EAX

5: const INT * & ri = pi;

00401035 LEA ECX, [EBP-8]

00401038 MOV DWORD PTR [EBP-0CH], ECX

The above is the assembly code I got in the VC. The sixth line clearly shows the address of the pointer to the A variable, rather than what we imagine the address of the A variable. So once we use const Int * PI = & a This statement assigns a reference pointer, then the assembly of the compiler will save the address of the A variable in a register and then pass the address of the register to the RI. These operations. Do you find anything wrong? Yes, the address of the register cannot be used directly, so the compiler cannot generate the target code of that statement, naturally to report an error.

转载请注明原文地址:https://www.9cbs.com/read-111858.html

New Post(0)