Advertisement
Beginner C++, Type Deduction & auto

What is the difference between auto, auto&, and const auto&?

Short answer

auto deduces a value type (a copy, dropping references/top-level const). auto& deduces a (mutable) reference to the source, avoiding a copy and allowing modification. const auto& deduces a const reference—no copy, read-only—ideal for iterating large objects without copying.

Save C++ mock interview
Advertisement
AModel answer
auto deduces a value type (a copy, dropping references/top-level const). auto& deduces a (mutable) reference to the source, avoiding a copy and allowing modification. const auto& deduces a const reference—no copy, read-only—ideal for iterating large objects without copying. Choosing the right form controls copies and mutability.
for (auto x : v)        // copies each element
for (auto& x : v)       // reference, can modify
for (const auto& x : v) // no copy, read-only
Real-world example
Switching a range-for from auto to const auto& stops copying large strings on each iteration.
Likely follow-ups
  • Which form copies? | When use const auto&?
Related topics