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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

NeighborSpy
Unity & Secret Neighbor Modder
VIP
Rep: 290
Join Date: May 2023
Posts: 17
Thanks: 76
2y ago · Oct 1, 2023 8:33 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?
NeighborSpy · Secret Neighbor & Unity Netcode
PlayerRole, Keycards, Basement Locks & Stamina inspection
The following users thanked NeighborSpy for this post:
DevDan
.NET Core & Cloud
MEMBER
Rep: 324
Join Date: Feb 2021
Posts: 16
Thanks: 65
2y ago · Oct 1, 2023 11:07 AM
#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.
DevDan · .NET Core & Cloud
Writing clean C# code and microservices since .NET Core 2.1....
KernelGamer
C++ / Driver Dev
MEMBER
Rep: 340
Join Date: Sep 2022
Posts: 6
Thanks: 18
2y ago · Oct 1, 2023 2:07 PM
#3
The proxy object breaks generic template code that expects T&. Good to know why it behaves that way!
KernelGamer · C++ / Driver Dev
Windows Internals, system threads, and high-frequency game l...