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.
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.
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.
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