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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

ApexPredator_
Source Engine Modder
VIP
Rep: 340
Join Date: May 2022
Posts: 23
Thanks: 88
6y ago · Jan 1, 2020 7:00 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?
ApexPredator_ · Source Engine Specialist
The following users thanked ApexPredator_ for this post:
GlowShader
Shader & Overlay Artist
MEMBER
Rep: 185
Join Date: Oct 2023
Posts: 36
Thanks: 46
6y ago · Jan 1, 2020 9:15 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.
GlowShader | Shaders, Stencils & DirectX DrawLists
CitizenNative
RAGE Engine & FiveM Dev
VIP
Rep: 315
Join Date: Sep 2022
Posts: 21
Thanks: 82
6y ago · Jan 2, 2020 12:15 AM
#3
The proxy object breaks generic template code that expects T&. Good to know why it behaves that way!
CitizenNative | RAGE Engine & FiveM Native Calls