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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

RustMechanic
Unity & IL2CPP Reverser
VIP
Rep: 295
Join Date: Nov 2022
Posts: 32
Thanks: 74
6y ago · Jan 19, 2020 1:24 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?
RustMechanic | IL2CPP & Unity Engine Analysis
The following users thanked RustMechanic for this post:
KernelDiver
Kernel & Systems Researcher
VIP
Rep: 275
Join Date: Jan 2024
Posts: 24
Thanks: 70
6y ago · Jan 19, 2020 2:42 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.
KernelDiver · Windows Internals & Page Tables
DirectXRay
DirectX 12 / Vulkan Dev
MEMBER
Rep: 240
Join Date: Feb 2023
Posts: 31
Thanks: 60
6y ago · Jan 19, 2020 5:42 PM
#3
The proxy object breaks generic template code that expects T&. Good to know why it behaves that way!
DirectXRay · DirectX 12 & Vulkan Command Lists