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