Daily C++ Puzzle 7

The binding that copied

A short C++ program with a bug: the binding that copied. The answer, the observed output, the fix, and the lesson are on this page.

#include <iostream>
#include <utility>

int main() {
    auto p = std::make_pair(1, 2);
    auto [a, b] = p;
    ++a;
    std::cout << "a=" << a << " p.first=" << p.first << '\n';
}

Plain auto structured bindings copy each element. ++a changes the copy, not the pair.

Observed output: a=2 p.first=1.

Fix: auto& [a, b] = p; to bind references.

Lesson: a structured binding follows the same copy-vs-reference rule as any other auto declaration.

Facts verified 2026-11-04. The code on this page was compiled and run on the box with GCC 16.2.0 at -std=c++23 -Wall -Wextra; the outputs quoted are the observed outputs. MSVC was not tested.

Back to the daily tips index

Keep Exploring

Keep exploring the docs, samples, and free tools to continue your evaluation.