To study the underlying implementation of the reference in C + +, write a small code to verify the rationale.
The reference is the alias of a variable, and in the end will it request memory space for the reference? If you apply for space, the space is stored, the following code is the main solution to this question.
The code is as follows, see code comments in detail
1#include <iostream>2#include <string>3#include <vector>4#include <algorithm>5 using namespacestd;6 7 classTest8 {9 Public:Ten intVal; One int&Ref_val; ATest (): Val (0xFFFFFFFF), Ref_val (Val) - { - } the }; - - intMain () - { + Test obj; -cout <<sizeof(obj) <<endl;//in VS2008, the result of Win7 32 bit is 8, indicating that the reference is also a memory space +cout << &obj<<endl;//0x001bfa28 Acout << & (Obj.val) <<endl;//0x001bfa28 atcout << & (Obj.ref_val) <<endl;//0x001bfa28 - - intI=0x01010101; - int*ptr = &i;// -cout << &i<<Endl; -cout << ptr <<Endl; incout <<& (*ptr) <<Endl; - to return 0; +}
Through the output, the following results can be obtained
1, the reference in memory will also allocate space, the space in which things are referred to the variable address, so the reference can be seen as a constant pointer ptr;
2, the reference to take the address operation, in fact, is the address of the referenced variable, the compiler will interpret the reference address as & (*PTR) address, the 29th line in the code confirms this statement
Run results
Memory results when debugging (memory results can be seen as small end little-ending mode)
The underlying implementation referenced in C + +