Contenido del Curso
C++ Smart Pointers
C++ Smart Pointers
References Best Practices
Naming conventions
Choose meaningful names for your references. The names should reflect the purpose of the referenced variable. Clear and descriptive names enhance code readability, and make it easier for others (or your future self) to understand your code.
main
In the above code, counterRef
is a meaningful name for a reference, whereas r
is a poor naming choice that should be avoided.
Scope and lifetime
Be mindful of the scope and lifetime of your references. As a general rule, don’t return references to local variables from functions, as it leads to undefined behavior once the variable goes out of scope.
main
In the above code we are returning a reference to localVar
, a local variable, from the function createReference
. This will lead to undefined behavior once localVar
goes out of scope.
References in range-based for loops
Use references in range-based for loops to work directly with the elements of a container, without creating unnecessary copies.
main
In the above code, we use references to iterate over a vector. This ensures that the vector entries are accessed directly, without any copying involved.
¿Todo estuvo claro?