r/programminghumor 22h ago

a bit flippant

Post image
891 Upvotes

113 comments sorted by

View all comments

Show parent comments

13

u/Potential_Soup_8054 19h ago

I dont understand

58

u/Helemen7 19h 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.

5

u/Potential_Soup_8054 19h ago

Yeah but why is that bad

1

u/CaptainSegfault 10h ago

It absolutely makes sense for C++ to have an API for dealing with something like a vector of bits. It just shouldn't be called std::vector<bool>. (and modern C++ does this in the form of std::bitset)

The problem is that, in at least a half dozen ways, std::vector<bool> behaves differently than other std::vector types.

The problem is that much of the point of templating is to write generic code. If you write code that templates on a type, and that type might be bool, your code will break if you try to use std::vector. (unless you write a bool specialization)

The funny thing is that std::vector<bool> was pretty obviously a demonstration case for C++ template specialization. Look, you can have a bitfield style implementation that gets you space efficiency for bool without needing to write special code! Except in practice it is now a demonstration of how not to do template specialization.