C++ / CHAPTER 02
Functions, references, and lifetime
IntermediateChoose copying or borrowing deliberately when a function receives data.
By the end of this chapter
- Distinguish value and reference parameters
- Use const references for read-only access
- Reject references to expired local objects
The idea
Enter this chapter knowing declarations, assignments, and function calls. A value parameter is a separate object initialized from its argument. Changing that parameter does not change the caller’s original integer. A reference parameter instead names the caller’s object, allowing a function to make an intentional update. The function signature therefore communicates an important part of its behavior, even before you read the body.
Use a const reference when a function only observes a larger object and should avoid copying it. A reference does not own its target or extend every possible lifetime. Returning a reference to an ordinary local variable leaves the caller referring to an object that has already ceased to exist. Prefer a returned value when the function creates a new result.
#include <iostream>
void copied(int value) { value += 3; }
void adjusted(int& value) { value += 3; }
int main() { int score=7; copied(score); adjusted(score); std::cout << score << "\n"; }10
The value parameter changes only its local copy. The reference parameter changes score itself, so only one addition reaches the caller.
Try it yourself
Write a read-only function taking const std::string& and returning its length.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING