In C++, why can worker threads writing different indices of a std::vector<bool> still race, and what else makes it unlike other vectors?
answer
- bits, not bools
- a proxy object in place of bool&
- two flags share one word
- the documented exception for concurrent writes
basics
~20 sstd::vector<bool> is a specialization that packs flags into bits, so operator[] returns a proxy object instead of bool&. Neighbouring flags share a word, so concurrent writes to different indices can race, and bool&, bool* and data() are unavailable.
solid answer
~50 s`std::vector<bool>` is a partial specialization; the standard recommends a space-optimized bit representation, and libc++ and libstdc++ both pack flags into words. A bit has no address, so `operator[]` returns `std::vector<bool>::reference`, a proxy class, and `const_reference` is plain `bool`. Writing through the proxy is a read-modify-write of the whole word, which is why the standard makes `vector<bool>` the one exception to the rule that different elements of a container can be modified concurrently: `y[0] = true` can race with `y[1] = true`. The proxy also breaks generic code: `bool& r = v[0]` and `for (auto& x : v)` do not compile, `auto x = v[0]` copies a proxy that writes back into the vector, and there is no `data()` or `bool*`. Use `std::vector<char>` or `std::vector<std::uint8_t>` when you need per-element writes, and `std::bitset<N>` for a fixed number of flags.
code
cpp · 18 lines#include <cstdio>
#include <type_traits>
#include <vector>
int main() {
std::vector<bool> alive(8, false);
auto flag = alive[2]; // a std::vector<bool>::reference proxy
static_assert(!std::is_same_v<decltype(flag), bool>);
flag = true; // writes through to alive[2]
std::printf("alive[2]=%d\n", int(alive[2]));
bool copy = alive[3]; // converting to bool makes a real copy
copy = !copy;
std::printf("copy=%d alive[3]=%d\n", int(copy), int(alive[3]));
// bool& ref = alive[0]; // does not compile: no bool object to bind to
}go deeper
Know that std::vector<bool> stores bits, so operator[] returns a proxy object rather than a bool reference.
Explain the proxy type, why bool& and data() are unavailable, and why auto x = v[i] keeps writing into the vector.
Diagnose the concurrent-write race on neighbouring flags, cite the standard's explicit exception, and pick a byte-per-flag or atomic replacement.
Decide when a codebase allows std::vector<bool>: weigh memory density against generic-code breakage and threading hazards, and set a default type for flag arrays.
## A specialization, not just a vector of bools The standard library declares a partial specialization `std::vector<bool, Allocator>`, provided, in the draft's words, "to optimize space allocation". The draft states that there is no requirement to store the data as a contiguous allocation of `bool` values and that a space-optimized representation of bits is recommended instead. libc++ and libstdc++ both follow the recommendation and pack the flags into machine words; libstdc++'s word type is `unsigned long`. A single bit has no address, so the specialization cannot hand out `bool&`. Instead: - `operator[]` on a non-const vector returns **`std::vector<bool>::reference`**, a class that simulates a reference to a single bit. It converts to `bool`, accepts assignment from `bool`, and has `flip()`. - `const_reference` is plain `bool`, so the const overload returns values, not references. - The iterators are proxy iterators, and the specialization has no `data()` member. ## What breaks in generic code Code written for `std::vector<T>` usually assumes that `v[i]` is a `T&`. With `bool` that assumption fails in visible and invisible ways: 1. **`bool& r = v[0];` does not compile.** Clang reports "non-const lvalue reference to type 'bool' cannot bind to a temporary of type 'reference'". The same failure appears inside templates, for example a `for (auto& x : v)` loop instantiated with `T = bool`. 2. **`auto x = v[0];` copies the proxy, not the value.** Assigning to `x` writes into the vector. The proxy refers into the vector's storage, so once the vector is destroyed or reallocates, using it is undefined behaviour. 3. **`&v[0]` is not a `bool*`**, and there is no `data()`, so the flags cannot be handed to a C API or viewed through `std::span<bool>`. 4. **Concurrent writes to different elements can race.** For the other containers, the standard requires implementations to avoid data races when different elements of the same container are modified concurrently, and it names `vector<bool>` as the exception: for a `vector<bool> y`, `y[0] = true` can race with `y[1] = true`. Both writes read, modify and write back the same word. 5. **It is not a sequence container.** A note in the draft says exactly that, so a component that requires a sequence container cannot count on it. ## The particle-system bug A particle update splits `std::vector<bool> alive` into interleaved or adjacent ranges and lets each worker thread clear the flags of particles that died in its range. Every thread writes different indices, so the code looks race-free, yet threads touching flags in the same word update that word concurrently. One thread's write-back can overwrite the other's, and a dead particle comes back to life. ThreadSanitizer reports this as a data race; without it the symptom is rare, non-deterministic and load-dependent, which is exactly the kind of bug that survives code review. The program has undefined behaviour, so no particular output can be relied on. ## What to use instead | Need | Choice | |---|---| | one byte per flag, real `bool&`, safe writes to distinct elements | `std::vector<char>` or `std::vector<std::uint8_t>` | | `bool` elements with real references | `std::deque<bool>` (not specialized) or `std::unique_ptr<bool[]>` | | a fixed, compile-time number of flags packed into bits, one writer | `std::bitset<N>` (also packed, with its own proxy `reference`) | | packed bits, single writer, proxy accepted | `std::vector<bool>` itself | `std::vector<bool>` is still reasonable when memory matters more than reference semantics: on these libraries it is eight times denser than a byte per flag, and a single thread writing it is fine. It is not deprecated. C++26 deprecates only one member, the static `swap(reference, reference)`. ## Spotting it in review - A template over the element type that takes `std::vector<T>&` and binds `auto&` or `T&` to elements: it fails to compile for `bool`, or, written with plain `auto`, compiles and silently writes through proxies. - A `std::vector<bool>` shared between threads or tasks, with writes to distinct indices. - Proxies kept in variables across a `push_back`, which may reallocate and leave them pointing into freed storage. ## Interview framing - Start with the proxy: why a bit cannot be referenced and what type `operator[]` returns instead. - List the consequences: no `bool&`, `auto` copies a proxy, no `data()`, and the data-race exception. - Finish with a replacement matched to the need rather than a blanket "never use it".
- Why does for (auto& x : flags) fail to compile when flags is a std::vector<bool>, while for (auto&& x : flags) works?Dereferencing the iterator yields a `std::vector<bool>::reference` prvalue, and a non-const lvalue reference cannot bind to a temporary. `auto&&` is a forwarding reference, so it binds to the temporary proxy and extends its lifetime for the loop body; assigning through it writes the bit back into the vector.
- How would you make the alive flags of a multithreaded particle update race-free without a lock?Store one byte per flag, for example `std::vector<std::uint8_t>`, so each element is a separate memory location and threads writing different indices do not conflict. If several threads may write the same index, each element needs to be atomic, for example `std::vector<std::atomic<std::uint8_t>>` created at its final size, since atomics cannot be moved during growth.
- std::vector<bool> stores each flag as a one-byte bool like any other vector
- Threads writing different indices of a std::vector<bool> can never race
- auto x = v[0] on a std::vector<bool> gives an independent bool copy
- std::vector<bool> is deprecated, so new code cannot use it
- You can pass v.data() of a std::vector<bool> to a C function taking bool*
Assumes C++23; the specialization's rules are unchanged since C++11, and C++26 deprecates only its static swap(reference, reference) member.