r/ProgrammerHumor • • 12d ago

Meme cppAndItsVectorBooleans

Post image
3.4k Upvotes

214 comments sorted by

View all comments

33

u/UnhappyJudge2487 12d ago

But bools as a standard are stored as bytes not bits. If you initiate a bool in cpp it's stored in a byte so it can be addressed

29

u/unknown_alt_acc 12d ago

std::vector<bool> may be specialized to store bools compactly and non-contiguously. It is the only initialization of std::vector for which this is allowed, but it is not guaranteed by the standard.

1

u/UnhappyJudge2487 12d ago

So the problem is that it could be done as but but wasn't?

35

u/unknown_alt_acc 12d ago

No, the problem is that the standard allows it at all.

All other instantiations of std::vector are guaranteed to store addressable objects contiguously. std::vector<bool> is arbitrarily allowed to break this guarantee. This can break generic code if you don't defensively program around it, which defeats the whole point of having a strong type system with robust generic programming facilities.

What really should have happened is simply using the type system for its purpose. std::vector<bool> should not have been specialized, and a separate container named something like std::dynamic_bitset should have been introduced to cover the cases where you do want to store compacted boolean values. This way,std::vector maintains a consistent contract and the type system gets used to better express the programmer's intent.

4

u/ivain 12d ago

Great explanation.

-5

u/nimrag_is_coming 12d ago

Sort of, the compiler is allowed to pack sequential book fields in classes into single bytes

10

u/unknown_alt_acc 12d ago

The compiler is absolutely not allowed to pack contiguous bools. That breaks the addressability requirement of objects. If you want packed Boolean values, the language gives you plenty of ways to express that.