Conteúdo do 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
int main() { int counter = 42; // Poor naming choice int& r = counter; // Improved naming for better clarity int& counterRef = counter; // Now it's clear that counterRef is a reference to the counter // ... rest of the code }
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
const int& createReference() { int localVar = 10; // This is dangerous - localVar goes out of scope return localVar; } int main() { const int& result = createReference(); // Undefined behavior }
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
#include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; // Use references in range-based for loop for (const int& num : numbers) { // Code that works with each element directly } }
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.
Obrigado pelo seu feedback!