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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

KeycardMaster
Item ESP & Unity UI Dev
MEMBER
Rep: 215
Join Date: Oct 2023
Posts: 19
Thanks: 54
2y ago · Oct 19, 2023 3:57 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?
KeycardMaster | Keycard & Objective ESP Specialist
The following users thanked KeycardMaster for this post:
PixelCraft
ImGui UI Hacker
MEMBER
Rep: 344
Join Date: Mar 2022
Posts: 7
Thanks: 92
2y ago · Oct 19, 2023 5:29 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.
PixelCraft · ImGui UI Hacker
Creating custom Dear ImGui themes, graphs, docking layouts, ...
BlazorKing
Full-Stack C#
MEMBER
Rep: 199
Join Date: Oct 2023
Posts: 6
Thanks: 26
2y ago · Oct 19, 2023 7:29 PM
#3
The proxy object breaks generic template code that expects T&. Good to know why it behaves that way!
BlazorKing · Full-Stack C#
Building real-time web applications and desktop tools with B...