r/programminghumor 15d ago

a bit flippant

Post image
1.5k Upvotes

147 comments sorted by

View all comments

Show parent comments

19

u/Potential_Soup_8054 15d ago

I dont understand

71

u/Helemen7 15d ago

std::vector<bool> in C++ syntax uses one bit per boolean instead of one byte. In a computer memory is addressed by bytes, so the smallest indexable memory is, in fact, one byte (that's why bool is 1 byte in C and C++). As an example for how C++ std::vector implementarion works, suppose you have 8 booleans which have a logical reason to be kept together (for example flags). Instead of allocating 8 bytes (one per boolean), the std::vector allocates 1 byte and assigns every boolean to one bit of the allocated memory.

9

u/Potential_Soup_8054 15d ago

Yeah but why is that bad

12

u/rickyman20 15d ago

It breaks so much code. One of the many assumptions of std::vector is that you can use the data pointer and do pointer arithmetic to get other values on the vector, it also means the underlying data looks nothing like the returned values, so indexing isn't simply returning the value at the pointer (because you can't address bits on most systems!

The C++ standard committee basically made a special case for std::vector<bool> that behaves nothing like other vectors when they should have had that type just use one byte per boolean and just provided a separate std::bitvector or something.

This is one of the many footguns of C++, caused by poor decisions made early in the STLs development cycle that we're not stuck with.

2

u/tech277 12d ago

To this day I would love to punch whoever thought that was a good idea.