C++C++ Explainer
C++ · 1 · Foundations2 / 36 · 6%

References & const-correctness

Prefer references over pointers when the value must not be null.

shortcuts: ← prev · → next · M mark
1

T&

An alias for another object. Cannot be rebound, cannot be null.

Example
example
int x = 5;
int& r = x;   // alias
r = 10;       // x is now 10
2

const T&

Pass big objects to functions without copying.

Example
example
void print(const std::string& s) {
    std::cout << s << '\n';
}
TIP
Rule of thumb: pass by const& for anything larger than a machine word.
3

const methods

A const method promises not to mutate the object.

Example
example
struct Point {
    int x, y;
    int sum() const { return x + y; }
};