Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::vector<bool>: specialization and proxy references

The std::vector<bool> specialization targets space savings, but mutable element access returns a proxy object rather than bool&.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <vector>
std::vector<bool> flags{true, false};

std::vector<bool> is a partial specialization (std::vector<bool> specialization) for Boolean values. Bit packing is recommended, not guaranteed; do not assume a contiguous array of bool objects.

Mutable operator[] returns std::vector<bool>::reference, a proxy object, not bool&. auto bit = flags[0] retains a connection to the element; bool snapshot = flags[0] copies its value. Access through a const vector returns bool.

flags.flip() complements every bit. In the example, assignment through bit changes the vector, but not snapshot.

Examples

#include <iostream>
#include <vector>

int main() {
    std::vector<bool> flags{false, true};
    auto bit = flags[0];
    bool snapshot = flags[0];
    bit = true;

    std::cout << std::boolalpha
              << snapshot << ' ' << static_cast<bool>(flags[0]) << '\n';

    flags.flip();
    std::cout << static_cast<bool>(flags[0]) << ' '
              << static_cast<bool>(flags[1]) << '\n';
}

Result

false true
false false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources