First, let’s address two questions
◆ What are the differences between pointers and references?
◆ When should we use pointers? When should we use references?
Differences between Pointers and References
See the code below:
A pointer is used to represent a memory address, and this pointer is the address of the variable it points to.
A reference is simply another name for a variable; it is also known as an “alias”.
Differences
◆ A pointer can be declared without initialization, but it must be checked each time it is used to prevent null pointer exceptions. In contrast, a reference can never be null; it must always refer to an object.
◆ A pointer stores an address and can be reassigned. A reference always points to the object it was initially assigned to.
Usage Scenarios for Pointers and References
References are primarily used as function parameters and return values. See the code below:
By using vec[3] = 3, we can change the value of the vector container. This is because the [] operator returns a reference. It essentially gives an alias to the internal variable, and the [] operator can also return a pointer, i.e., *vec[3] = 3. In fact, anything that can be done with references can also be done with pointers. So why use references?
Conclusion
Use the right tool for the right job.
Pointers can operate on anything in memory without constraints, making them very powerful but also dangerous. Therefore, references should be used at appropriate times.
When you need to point to something and ensure it never points to anything else, such as in some function parameters to avoid copying, you can use references. Alternatively, when implementing an operator that cannot be achieved with pointers due to syntax requirements, such as vec[3] = 3, you can use references. In all other cases, pointers should be used.