In C++, what do `auto`, `auto&` and `const auto&` deduce when initialized from a function returning `const Order&`?
answer
- auto behaves like a by-value parameter
- references and top-level const dropped
- low-level const survives
- plain auto makes a copy
basics
~10 sPlain auto deduces Order, dropping the reference and top-level const, so it copies. auto& deduces const Order&, keeping the referred-to const, and const auto& deduces const Order& too.
solid answer
~40 s`auto` is deduced like a by-value template parameter: references and top-level `const` and `volatile` are dropped, so `auto a = best_bid();` declares an `Order` and copies it, even though the function returns `const Order&`. With `auto&` the placeholder is deduced like `T&`; the `const` belongs to the referred-to object, which is low-level const, so it is kept and `b` is `const Order&`. `const auto&` gives the same type and states the read-only intent. The same low-level rule keeps `const` in `auto* p` for a pointer to `const`. Plain `auto` also decays arrays and functions to pointers. In a refactor, `auto` can therefore turn a cheap reference into a copy and a live view into a snapshot.
code
cpp · 22 lines#include <string>
#include <type_traits>
struct Order { std::string id; double px; };
int main() {
const Order o{"A1", 101.5};
const Order& r = o; // stands in for const Order& best_bid()
auto a = r; // Order: a copy
auto& b = r; // const Order&
const auto& c = r; // const Order&
auto* p = &o; // const Order*
static_assert(std::is_same_v<decltype(a), Order>);
static_assert(std::is_same_v<decltype(b), const Order&>);
static_assert(std::is_same_v<decltype(c), const Order&>);
static_assert(std::is_same_v<decltype(p), const Order*>);
auto x = 1.0f; // float
static_assert(std::is_same_v<decltype(x), float>);
(void)a; (void)b; (void)c; (void)p;
}go deeper
Recall that plain auto drops references and top-level const and therefore copies, while auto& and const auto& keep the const of what they bind to.
Explain top-level versus low-level const and map auto, auto& and const auto& onto by-value, T& and const T& deduction.
Review auto refactors for silent copies on hot paths and for references that became snapshots, and pin the intended type with const auto& or a static_assert.
Set the team default for read-only locals bound to returned references, and decide where an explicit type is clearer than any auto form.
## The rule in one line A variable declared with plain `auto` gets the type of its initializer **as a value**: references are dropped and **top-level** `const` and `volatile` are dropped. The declaration then makes a new object, a copy (or a move from a temporary). Adding `&`, `const` or `*` around `auto` changes what is deduced, because, braced initializers aside, the placeholder is deduced the way a function template parameter of that shape would be: `auto` behaves like `T` in `template<class T> void f(T)`, `auto&` like `T&`, and `const auto&` like `const T&`. Template argument deduction itself is its own subject; for variables you only need the patterns below. ## The four forms side by side Take a trading gateway where `const Order& best_bid();` returns a reference into the order book: | Declaration | Deduced type of the variable | What happens | |---|---|---| | `auto a = best_bid();` | `Order` | copies the order | | `auto& b = best_bid();` | `const Order&` | binds to the book's order, read-only | | `const auto& c = best_bid();` | `const Order&` | same, and states the intent | | `auto* p = &book.front();` (on a `const` book) | `const Order*` | pointer; the pointee's `const` is kept | Why does `auto&` keep the `const`? Because for a reference, the `const` belongs to the referred-to type, not to the variable; it is **low-level** const, and only top-level qualifiers are dropped. The same applies to `auto*`: the `const` in `const Order*` describes the pointee, so it stays, while a `const` on the pointer itself (`Order* const`) would be dropped by plain `auto`. ## Other things plain `auto` strips - **Arrays decay**: with `int ticks[8];`, `auto t = ticks;` is an `int*`, while `auto& t = ticks;` is an `int(&)[8]` that still knows its size. - **Functions decay** to function pointers in the same way. - **The literal decides**: `auto x = 1.0f;` is `float`, `auto n = 0;` is `int`, `auto q = 0u;` is `unsigned int`, and `auto big = 3'000'000'000;` is whatever integer type the literal has (`long` on common 64-bit Unix platforms). - `auto` **requires an initializer**, so `auto qty;` does not compile. ## Why the copy matters in a refactor Replacing `const Order& bid = book.best_bid();` with `auto bid = book.best_bid();` looks like a harmless cleanup, but it changes the program in two ways: 1. **Cost**: every call now copies an `Order`, including any `std::string` members, which can mean a heap allocation on a hot path. 2. **Meaning**: `bid` is a snapshot. If the book updates the order later, a reference would see the new price and the copy will not. Sometimes the snapshot is what you want; the point is that the refactor silently chose it. The repair is to say what you mean: `const auto& bid = book.best_bid();` for a read-only view, `auto bid = ...` only when a copy is intended. ## Range-for follows the same rules A range-based `for` declares its loop variable from `*it` for each element, so the same three forms apply: - `for (auto o : orders)` copies every `Order`; changes to `o` do not reach the container; - `for (auto& o : orders)` binds to each element and can modify it (or is `const Order&` if `orders` is const); - `for (const auto& o : orders)` binds read-only and copies nothing. In a gateway loop that runs on every tick, the difference between the first and the third form is one copy per order per tick. ## Checking what was deduced A quick way to verify deduction in code, rather than trusting a tooltip, is a compile-time check: ```cpp static_assert(std::is_same_v<decltype(bid), const Order&>); ``` `decltype` applied to a variable's name reports its declared type, so this assertion fails to compile if the refactor changed `bid` into a copy. The full rules of `decltype`, including the parenthesized form, are worth a question of their own. ## Pitfalls to name 1. Thinking `auto` keeps the reference because the function returns one. 2. Thinking `auto&` drops `const` and allows writing to a `const` object. 3. Expecting `auto` on an array to keep the array type. 4. Writing `auto& x = make_order();` with a function returning by value: a non-const lvalue reference cannot bind to the temporary, so it fails to compile, while `const auto&` binds and extends the temporary's lifetime.
- What does `auto* p = &o;` deduce when `o` is `const Order`, and what does `auto q = p;` deduce?`&o` has type `const Order*`, and the `const` describes the pointee, so it is low-level and kept: `p` is `const Order*`. `auto q = p;` copies the pointer and is also `const Order*`; only a `const` on the pointer itself, as in `const Order* const`, would be dropped by plain `auto`.
- Why does `auto& o = make_order();` fail to compile when `make_order` returns `Order` by value?Deduction gives `Order&`, a non-const lvalue reference, which cannot bind to the prvalue the call produces. `const auto& o = make_order();` deduces `const Order&`, binds to the materialized temporary and extends its lifetime to the reference's scope; plain `auto o = make_order();` initializes `o` directly from the prvalue.
- auto keeps the reference when the function returns a reference.
- auto& drops const, so the bound object can be modified.
- auto deduces the declared return type exactly, qualifiers included.
- auto on an array variable deduces the array type.
- const auto& always makes a copy first.