Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
References Best Practices | References
C++ Smart Pointers
course content

Course Content

C++ Smart Pointers

C++ Smart Pointers

1. Introduction to Smart Pointers
2. Unique Pointers
3. Shared Pointers
4. Weak Pointers
5. References
6. Advanced topics

bookReferences 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.

cpp

main

copy
123456789101112
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.

cpp

main

copy
12345678910
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.

cpp

main

copy
12345678910
#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.

Why should you avoid returning references to local variables from functions?

Why should you avoid returning references to local variables from functions?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 4
some-alt