Daily C++ Puzzle 5

auto that did not copy

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

#include <iostream>
#include <vector>

int main() {
    std::vector<bool> v = {true, false};
    auto first = v[0]; // not a bool
    bool copy = v[0];  // a real bool
    v[0] = false;
    std::cout << "first=" << first << " copy=" << copy << '\n';
}

vector<bool> is specialized — v[0] returns a proxy object that refers to the bit, not a bool. auto deduces the proxy type, so first still points at the bit and follows the later change; bool copy takes a real copy.

Observed output: first=0 copy=1.

Fix: spell the type (bool first = v[0];) or avoid vector<bool> where value semantics matter.

Lesson: auto deduces what the expression returns, and for vector<bool> that is a proxy.

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.