Advertisement
Advanced C++, Type Deduction & auto

Why does auto strip references and top-level const, and when is that a problem?

Short answer

auto uses value (by-copy) deduction like a by-value template parameter, so it drops references and top-level const to give an independent copy.

Save C++ mock interview
Advertisement
AModel answer
auto uses value (by-copy) deduction like a by-value template parameter, so it drops references and top-level const to give an independent copy. This is usually desirable, but it's a problem when you intended to alias or avoid copying—then you must write auto&, const auto&, or use decltype(auto). Forgetting this silently introduces copies.
const int& getRef();
auto x = getRef();       // int copy (const & dropped)
const auto& y = getRef(); // const int& (no copy)
Real-world example
A subtle performance bug: auto copies a large object returned by const-reference until changed to const auto&.
Likely follow-ups
  • How do you preserve the reference? | Why is this a silent bug?
Related topics