Contenido del Curso
C++ Smart Pointers
C++ Smart Pointers
How Are References Different From Pointers?
Understanding references
In the first section, we saw that references are aliases for existing variables. The main thing they do is provide an alternative syntax for accessing the value of an object. If we look under the hood, the memory address of a reference is the same as the memory address of the referenced object.
main
If you run the above code, you will see that both the variable num
and the reference refNum
will have the same values, and the same memory addresses.
A reference is essentially a constant pointer
Another way to think about it is that a reference is essentially a constant pointer. A constant pointer is a pointer that can’t be reassigned to a different dynamic object after initialization. However, a constant pointer has to be dereferenced to get the value of the dynamic object. With references, you don’t have to dereference because you can access the value directly. Let’s consider an example for more clarity:
main
In the above code, we are demonstrating many things. First, we are creating a constant pointer and a reference. Then, we show that neither of them can be reassigned. Finally, we print their values: For the constant pointer we have to use *
for dereferencing, but the reference can be accessed directly. Play around with the code to learn more, while following the comments!
Setting to NULL | Can be set to NULL | Cannot be set to NULL |
Address in memory | Has its own address in memory | Does not have its own address in memory |
Initialization | Can be left uninitialized | Must be initialized or causes compiler error |
Pointer to another pointer | Possible | Not possible |
Array creation | Array of pointers can be created | Array of references cannot be created |
Accessing class/struct members | Use -> to access members | Use . to access members |
¿Todo estuvo claro?