r/ProgrammerHumor • • 12d ago

Meme cppAndItsVectorBooleans

Post image
3.4k Upvotes

214 comments sorted by

View all comments

Show parent comment

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.