C++20 sections · 1024 units
Open in Course

Const References

Safe and efficient

Pass by reference without allowing modification using const. This gives efficient access without risk of changes. You get speed of references with safety of pass by value. Example: void print(const Point &p) { cout << p.x; }.

The const prevents modifying p. Try p.x = 10; inside and the compiler errors. Read but don't change. This is best for large structs you don't want to modify. No copying overhead, no accidental mutations.

If a function just reads data, use const & for parameters.