References & const in C++
A reference is a second name for the same object; const & is C++'s read-only borrow.
#include <string>
void shout(std::string &word) {
word += "!";
}
std::size_t measure(const std::string &word) {
return word.size();
}
std::size_t demonstrate() {
std::string greeting = "hello";
std::string &alias = greeting; // same object, second name
shout(alias);
return measure(greeting);
}
How it works
shouttakesstd::string &, so appending"!"changes the caller's string in place.measuretakesconst std::string &: no copy is made and no edit is allowed.std::string &alias = greetingbinds a new name; mutating through it mutatesgreeting.
Keywords and builtins used here
constdemonstratemeasurereturnshoutsize_tvoid
The run, in numbers
- Lines
- 16
- Characters to type
- 300
- Tokens
- 85
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 68 seconds.
Step 2 of 3 in Values & references, step 2 of 27 in Language basics.