Home / Forums / Why does std::vector<bool> behave differently from other std::vector types? [Discussion #8]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

Why does std::vector<bool> behave differently from other std::vector types? [Discussion #8]

OptiMax
Benchmark Specialist
MEMBER
Rep: 95
Join Date: Apr 2023
Posts: 6
Thanks: 31
3y ago · Apr 19, 2023 11:51 AM
#1
I tried passing a reference to an element in std::vector<bool> and got a compiler error. Why is std::vector<bool> specialized differently?
OptiMax · Benchmark Specialist
BenchmarkDotNet, micro-optimizations, and zero-GC hot paths....
The following users thanked OptiMax for this post:
SpanSpecialist
Zero-Copy Memory
MEMBER
Rep: 273
Join Date: Aug 2021
Posts: 7
Thanks: 33
3y ago · Apr 19, 2023 2:09 PM
#2
std::vector<bool> is a historical space-optimization specialization that packs 8 booleans into each single byte! Because individual bits cannot have a memory address, operator[] returns a proxy object (std::vector<bool>::reference) instead of bool&. If you need a standard container of booleans with true references, use std::vector<uint8_t> or std::deque<bool> instead.
SpanSpecialist · Zero-Copy Memory
Span<T>, ReadOnlySpan<T>, and stackalloc for fast substring ...
HexRays99
Senior Reverse Engineer
VIP
Rep: 380
Join Date: Apr 2022
Posts: 36
Thanks: 94
3y ago · Apr 19, 2023 6:09 PM
#3
The proxy object breaks generic template code that expects T&. Good to know why it behaves that way!
HexRays99 · Reverse Engineering & Static Analysis
CPP
// Always check your pointers!
if (!pLocalPlayer) return;