Advertisement
Beginner C++, Const Correctness

Why should you pass objects by const reference?

Short answer

Passing large objects by const reference (const T&) avoids copying (better performance) while promising not to modify the argument (safer, clearer interface, and callable with temporaries and const objects).

Save C++ mock interview
Advertisement
AModel answer
Passing large objects by const reference (const T&) avoids copying (better performance) while promising not to modify the argument (safer, clearer interface, and callable with temporaries and const objects). It's the standard way to pass read-only parameters that are expensive to copy, like strings and containers.
void process(const std::vector<int>& data); // no copy, read-only
Real-world example
Changing a parameter from by-value to const reference removes a costly copy of a large vector on every call.
Likely follow-ups
  • What does it avoid? | Can it accept temporaries?
Related topics