Advertisement
Beginner C++, Const Correctness

What is a constant reference and why is it useful?

Short answer

A const reference (const T&) is a reference through which the referent can't be modified.

Save C++ mock interview
Advertisement
AModel answer
A const reference (const T&) is a reference through which the referent can't be modified. It's useful for read-only aliasing without copying, for function parameters, and because a const reference can bind to a temporary (extending its lifetime to the reference's scope), which a non-const lvalue reference cannot.
const std::string& r = std::string("temp"); // binds temporary
Real-world example
A function takes const std::string& so it can be called with both variables and string literals without copying.
Likely follow-ups
  • Can a const reference bind to a temporary? | Why can't a non-const lvalue reference?
Related topics