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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

DirectX_Pro
DirectX 11/12 Engineer
MEMBER
Rep: 69
Join Date: Aug 2021
Posts: 6
Thanks: 93
6y ago · Jul 1, 2020 10:06 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?
DirectX_Pro · DirectX 11/12 Engineer
Direct3D pipelines, compute shaders, and swap chain presenta...
The following users thanked DirectX_Pro for this post:
ImGuiArtist
Modern UI Designer
MEMBER
Rep: 227
Join Date: Dec 2025
Posts: 6
Thanks: 63
6y ago · Jul 1, 2020 12:22 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.
ImGuiArtist · Modern UI Designer
Dark glassmorphism, animated sliders, and custom font render...
GameDevSam
Indie Game Developer
VIP
Rep: 90
Join Date: Jul 2020
Posts: 8
Thanks: 22
6y ago · Jul 1, 2020 5:22 PM
#3
The proxy object breaks generic template code that expects T&. Good to know why it behaves that way!
GameDevSam · Indie Game Developer
Solo indie dev building games with Unity, Monogame, and cust...