An example of the relationship between reference and pointer in C++

  • 2020-05-24 05:53:30
  • OfStack

An example of the relationship between reference and pointer in C++

1. References must be initialized at the time of definition; Pointers are not required


int &rNum; // Uninitialized cannot be compiled  
int *pNum; // can  

2. 1 once a reference is initialized to point to an object, it can no longer be pointed to

Other objects, while Pointers can point to any object of the same type at any time


int iNum = 10; 
int iNum2 = 20; 
int &rNum = iNum; 
&rNum = iNum2; // Can't pass  

3. There is no NULL reference, but there is an NULL pointer.


int *pNum = NULL; // can  
int &rNum = NULL;// Can not be  

4. Different meaning in sizeof: the reference result is the size of the reference type,

But the pointer is always the number of bytes in the address space.


char c1 = 1; 
char* pc = &c1; 
char& rc = c1;
cout<<sizeof(pc)<<sizeof(rc)<<endl; // The output 4 1 

5. The content of the variable is changed by adding the reference, and the pointer is changed by adding the pointer


rNum++; // The contents of the pointer change  
pNum++; // Pointer to change  

6. There are multiple Pointers, but no multiple references


int &&rNum ; // Can not be  
int **ppNum; // can  

References are safer to use than Pointers

The underlying implementation of Pointers and references


int Num = 10;
012213BE mov     dword ptr [Num],0Ah 
int &rNum = Num;
012213C5 lea     eax,[Num] 
012213C8 mov     dword ptr [rNum],eax 
int *pNum =&Num;
012213CB lea     eax,[Num] 
012213CE mov     dword ptr [pNum],eax 

The underlying implementation is the same and is implemented as a pointer

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: