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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

LinQ_Lover
C# Developer
MEMBER
Rep: 313
Join Date: Jul 2020
Posts: 8
Thanks: 27
6y ago · Jul 10, 2020 4:42 PM
#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?
LinQ_Lover · C# Developer
Clean code, fluent LINQ expressions, and expressive C# patte...
The following users thanked LinQ_Lover for this post:
MathMagician
Vector Math & Physics
MEMBER
Rep: 219
Join Date: Nov 2024
Posts: 8
Thanks: 19
6y ago · Jul 10, 2020 6:25 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.
MathMagician · Vector Math & Physics
Quaternions, transformation matrices, and physics simulation...
JsonSpeedster
Serialization & I/O
MEMBER
Rep: 82
Join Date: Jun 2025
Posts: 7
Thanks: 87
6y ago · Jul 11, 2020 9:25 PM
#3
The proxy object breaks generic template code that expects T&. Good to know why it behaves that way!
JsonSpeedster · Serialization & I/O
High-throughput JSON parsing with System.Text.Json, Utf8Json...