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.
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-onlyReal-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