const References and When to Use Them
Pass large objects efficiently and safely with const references.
What const Reference Promises
A const T& says: "I will not modify what I refer to." The compiler enforces it.
void print(const std::string& s) {
// s.clear(); // ERROR: s is const
std::cout << s;
}Why Not Just Pass by Value?
Copying large objects is wasteful. A const reference is essentially free (it is just a pointer under the hood) and never lets the function modify the caller s data.
All lessons in this course
- Why References Aliases for Variables
- Pass-by-Value vs Pass-by-Reference
- const References and When to Use Them
- Reference Lifetime and Dangling References