auto
Prev: builtins | Up: builtins | Next: constexpr & consteval
Rel: References & Rvalues, Structured Bindings, Templates
Ref: cppreference — auto
Tags: #public #prog #cpp #builtins #tier/core
Overview
auto deduces a variable's static type from its initializer at compile time using the same rules as template argument deduction. By default, plain auto drops top-level const and references (making a copy), so add & or const auto& when you want to borrow without copying.
Usage
auto count = 42; // int
const auto& name = user.name(); // borrows without copying
auto& item = items[0]; // mutable reference
auto&& fwd = get_value(); // forwarding (universal) reference
// Abbreviated function template (C++20)
auto add(auto a, auto b) {
return a + b;
}
Gotchas
auto x = vec;copies the entirestd::vector; writeconst auto& x = vec;unless a copy is intended.- Avoid
autowith proxy-returning types likestd::vector<bool>(whereauto b = flags[0];deduces a proxy object rather thanbool).
Linked from
Related notes
- tuts/cpp/builtins/constexpr Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/structured_bindings Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins Linked here; links to this page; shared tags: #builtins, #cpp, #prog
- tuts/cpp/builtins/lambdas links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/references_and_rvalues Linked here; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/templates Linked here; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/c_style_casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/classes_and_virtual shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/concepts shared tags: #builtins, #cpp, #prog, #tier