CKTIS / C++
C++ structured bindings with `auto [a, b, c]`
A structured binding names the components of one object. Choosing `auto`, `auto&`, or `const auto&` changes how that object is stored or referred to.
Version: ISO C++23; implementation support may vary
Syntax
auto [a, b, c] = expression;
auto& [a, b, c] = lvalue;
const auto& [a, b, c] = expression;auto [a, b, c] = expression; introduces three new names in the current scope. The part before [ applies to one hidden variable, not to three independent auto declarations. The syntax was introduced in C++17. This entry covers ISO C++23; implementation support may vary.
Built-in arrays decompose by index. Tuple-like types such as std::tuple, std::pair, and std::array decompose by position using their tuple protocol. Other eligible classes decompose into all their non-static data members in declaration order. These members must either all be direct members of the class or all be members of the same base class. Each member must be accessible in the context of the structured binding declaration: an inaccessible member is not skipped and makes the declaration ill-formed. In C++23 the number of names must match the decomposition size: std::pair takes two, not three.
For a named tuple that stores values, auto makes a hidden copy, while auto& binds to the original elements, so writing through a binding changes the original. const auto& gives read-only access to ordinary value elements without copying the tuple; binding directly to a temporary tuple can extend its lifetime to that of the hidden reference. Reference elements, such as those produced by std::tie, still refer to the same objects even with auto; the binding does not extend those objects’ lifetimes.
std::get<0>(t) returns a reference to the first element of tuple t without declaring a name. std::tie(u, v, w) = t; assigns to existing variables through a tuple of references. A structured binding instead introduces new names.
Examples
#include <iostream>
#include <tuple>
int main() {
std::tuple<int, int, int> values{1, 2, 3};
auto [a, b, c] = values;
a = 9;
std::cout << a << ' ' << std::get<0>(values) << '\n';
auto& [x, y, z] = values;
x = 7;
std::cout << x << ' ' << std::get<0>(values) << '\n';
}
Result
9 1 7 7
The first line (`9 1`) shows the copy changing; the second (`7 7`) shows `x` changing the original tuple.
Related lessons
- C++ · Lesson 32 · Intermediate · Version: 2