r/ProgrammerHumor • • 14d ago

Meme cppAndItsVectorBooleans

Post image
3.4k Upvotes

214 comments sorted by

View all comments

69

u/0xbenedikt 14d ago

I think the behavior of it is quite logical. Bits are supposed to be one bit in size. If you have them in isolation, they will have to expand to at least 8 bits, but once they are a vector, you give permission to the compiler to pack and optimize them. If you can't have them optimized, use a type that guarantees an individual address, if that is what you need

41

u/the_horse_gamer 13d ago

you give permission to the compiler

this is library level behavior, not a compiler optimisation

it breaks many invariants

the correct solution would have been to make std::dynamic_bitset

7

u/Thrawn89 13d ago

Maybe optimize the memory footprint, but if it packs them, then the underlying memory hardware wont be able to just write to them directly.

All of a sudden you double your access bandwidth on writes since they may be promoted to read-modify-writes.

3

u/0xbenedikt 13d ago

It depends a lot on what platform the software runs on. C++ runs on everything from 8-bit microcontrollers to high performance compute platforms. On a microcontroller there often is an instruction that modifies a bit in a single cycle, while it is more costly on other platforms

2

u/narrill 13d ago

I think the behavior of it is quite logical. Bits are supposed to be one bit in size.

A bool in C++ isn't a bit.

4

u/0xbenedikt 13d ago

Yes and no. A bool variable is 8 bits, since by specification it needs its own address. But the information encoded in one bool is supposed to be one bit

3

u/narrill 13d ago

The information encoded doesn't matter; within C++'s type system, a bool is not a bit. Meaning, vector<bool> does not actually hold any bools, and any code that attempts to interact generically with a vector that happens to be a vector<bool> may be subtly broken.

Threading is the most obvious culprit here. For any other element type it's safe for different threads to read and write to different elements of the vector. For vector<bool> it isn't, because its elements are always read and written to in groups of eight.