skip to content

Should a C++ trading-gateway codebase adopt 'almost always auto' for locals, and where should explicit types remain mandatory?

level: principalimportance: should knowfreq 35%

answer

  1. initialization guaranteed, conversions avoided
  2. proxies and hidden copies
  3. numeric intent in domain code
  4. interfaces stay explicit

basics

~20 s

Adopt auto as the default for locals where the type is evident or unnameable, since it forces initialization and avoids silent conversions, but keep explicit types for numeric domain values, public interfaces, intended conversions and proxy-returning expressions.

solid answer

~40 s

AAA makes `auto` the default for locals. It guarantees initialization, avoids narrowing such as `int n = v.size();`, survives refactors, and prevents hand-typed mistakes like the map-entry copy; since C++17's guaranteed elision even `auto m = std::mutex{};` compiles. The costs are real: `auto` captures proxies like `std::vector<bool>::reference` and expression templates, makes copies the shortest form to type, hides numeric widths (`auto qty = 0;` is `int`) and makes code reviews harder without an IDE. For a gateway I would default to `const auto&` and `auto` for iterators, range-for, lambdas and types already named on the line, and require explicit types for prices, quantities and timestamps, public signatures, intended conversions and proxy-returning calls, backed by warnings and `static_assert`.

code

cpp · 15 lines
cpp
#include <cstdint>
#include <mutex>
#include <vector>

int main() {
    auto m = std::mutex{};          // C++17: guaranteed elision, no move needed
    std::vector<bool> flags(4);
    auto f = flags[0];              // std::vector<bool>::reference, a proxy, not bool
    flags[0] = true;
    bool now = f;                   // true: f refers into flags
    std::uint32_t qty = 70000;
    auto half = qty / 2u;           // stays std::uint32_t
    (void)m; (void)half;
    return now ? 0 : 1;
}

go deeper

for a junior

Recall that auto needs an initializer and deduces from it, and that it can deduce surprising types such as proxies.

for a middle

Explain the concrete bugs AAA prevents and the ones it introduces, with vector<bool> and map-entry copies as examples.

for a senior

Show how auto interacts with refactors, copies and numeric widths in real code, and which compiler warnings back the rule.

for a principal

Own the team rule: where auto is the default, where explicit types are mandatory, how interfaces are treated, and how tooling enforces the split.

## What the rule says "Almost always auto" (AAA) is a C++ style in which local variables are declared with `auto` by default: `auto qty = 0;`, `auto it = book.find(id);`, `auto order = Order{"A1", 101.5};`. When a specific type is wanted, it goes on the right-hand side (`auto n = std::int64_t{0};`) instead of the left. The question for a lead is not whether `auto` is good, but whether to make it the **default** in a codebase, and where to forbid it. ## What it buys - **No uninitialized variables.** `auto` needs an initializer, so `auto px;` does not compile, while `double px;` compiles and leaves an indeterminate value. - **No silent conversions on initialization.** `int n = orders.size();` converts a `std::size_t` to `int`, possibly losing range; `auto n = orders.size();` keeps the container's size type. - **Refactor resilience.** If `find` starts returning a different iterator type, every `auto it` follows. - **No hidden temporaries from mistyped types**, such as the `std::pair<std::string, Order>` copy in a map loop. - **Fewer long iterator and template types** in reading paths. C++17 removed a classic objection: before guaranteed copy elision, `auto m = std::mutex{};` did not compile (`call to deleted constructor of 'std::mutex'` under `-std=c++14`), so AAA could not be used for non-movable types; since C++17 it compiles. ## What it costs - **Proxy types.** `auto f = flags[0];` on a `std::vector<bool>` is a `std::vector<bool>::reference`, a proxy that refers into the vector; the same happens with expression-template math libraries, where `auto` captures an unevaluated expression that may refer to temporaries. - **Hidden copies.** `auto bid = book.best_bid();` copies where `const auto&` would bind; the default makes the costly form the shortest one to type. - **Numeric intent disappears.** `auto qty = 0;` is an `int`, which can overflow where the domain needs `std::int64_t`; `auto px = 101.5;` is a `double` even where the gateway stores prices as fixed-point integers. - **Review without an IDE.** In a diff view, `auto r = submit(order);` does not say whether `r` is a status code, a `std::expected` or a future. - **Brace surprises.** `auto x = {1};` deduces `std::initializer_list<int>`. ## A rule that holds up in a gateway There is no single right answer; it depends on the team's tooling and on how much of the code is numeric domain logic. A defensible middle position: | Use `auto` | Spell the type | |---|---| | iterators and range-for variables (`const auto&`) | money, prices, quantities, timestamps: fixed-width or domain types | | when the type is already on the line: `make_unique`, casts, constructors | function parameters and return types in public headers | | lambdas and other unnameable types | when a conversion is the point: `std::string s = view;` | | long template-dependent types in implementation code | when the initializer may be a proxy or an expression template | Then: 1. **Default the form, not just the keyword**: `const auto&` for read-only bindings, `auto` only for intended copies. 2. **Keep interfaces explicit**: deduced return types in headers tie callers to implementation bodies and change silently when a body changes. 3. **Back the rule with the compiler**: warnings such as `-Wrange-loop-construct` catch the copy cases, and `static_assert` pins types that must not drift. 4. **Revisit numeric code separately**: a team that bans `auto` for domain numbers loses little and gains explicit widths where overflow matters. ## Rolling the rule out A style rule is cheap to write and expensive to apply to a large gateway codebase. A rollout that does not stall feature work: 1. Apply it to **new and touched code** only; a mass rewrite of declarations produces a diff nobody can review and risks silent copies. 2. Turn on the compiler warnings that catch the costly cases (range-loop copies, dangling returns) before relaxing the rule, so `auto` lands on a safety net. 3. Write the exceptions down with examples from the codebase itself, especially the numeric domain types. 4. Revisit after a few months by reading review comments: if reviewers keep asking "what type is this?", the default is too wide for the team's tools. ## How to argue it in an interview A principal answer names the trade-off precisely: AAA removes whole classes of bugs (uninitialized locals, narrowing on assignment, mistyped container types) and introduces others (proxies, unintended copies, invisible numeric types). The decision is about which mistakes the team makes more often, what review tooling it has, and whether domain types are already strong enough that `auto` cannot hide the important information.

  • How do you keep AAA from hiding a 32-bit quantity that should be 64-bit?
    Put the type on the right-hand side or ban `auto` for domain numbers: `auto qty = std::int64_t{0};` or `std::int64_t qty = 0;`. Better still, introduce strong types such as `Quantity` and `Price`, so `auto` deduces a type that carries the unit and width, and arithmetic between incompatible kinds does not compile.
  • Why is a deduced `auto` return type in a public header a different decision from `auto` locals?
    A deduced return type is part of the interface but comes from the body, so callers must see the definition and the type changes whenever the body changes, possibly breaking them without a signature diff. Locals have no such reach. Most teams keep explicit return types in public headers even when they adopt AAA internally.

  • auto always makes code faster because it avoids conversions.
  • auto cannot be used with non-movable types like std::mutex in C++17.
  • auto f = v[0]; on a std::vector<bool> deduces bool.
  • Using auto everywhere removes the need for code review of types.
  • Banning auto entirely is the only safe choice for financial code.