C++ references – are they just syntactic sugar?

Assume reference as a pointer that:

  1. Can’t be NULL
  2. Once initialized, can’t be re-pointed to other object
  3. Any attempt to use it will implicitly dereference it:

    int a = 5;
    int &ra = a;
    int *pa = &a;
    
    ra = 6;
    
    (*pa) = 6;
    

here as it looks in disassembly:

    int a = 5;
00ED534E  mov         dword ptr [a],5  
    int &ra = a;
00ED5355  lea         eax,[a]  
00ED5358  mov         dword ptr [ra],eax  
    int *pa = &a;
00ED535B  lea         eax,[a]  
00ED535E  mov         dword ptr [pa],eax  

    ra = 6;
00ED5361  mov         eax,dword ptr [ra]  
00ED5364  mov         dword ptr [eax],6  

    (*pa) = 6;
00ED536A  mov         eax,dword ptr [pa]  
00ED536D  mov         dword ptr [eax],6  

the assigning to the reference is the same thing from the compiler perspective as the assigning to a dereferenced pointer. There are no difference between them as you can see (we are not talking about compiler optimization right now)
However as mentioned above, references can’t be null and have stronger guarantees of what they contains.

As for me, I prefer using references as long as I don’t need nullptr as a valid value, values that should be repointed or values of different types to be passed into (e.g. pointer to interface type).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)