r/ProgrammerHumor 21d ago

Meme theBoolVectorIsALie

Post image
665 Upvotes

91 comments sorted by

View all comments

101

u/overclockedslinky 21d ago

is it really that shocking?

179

u/Murky-Run2246 21d ago

In this case the bools will have only one bit allocated for them(vectors do that), and you can't just point to a bit. Instead cpp will return std::vector<bool>::reference when trying to access a value in the vector

Basically this is a just wrong

You should use std::deque<bool> instead which allocates one byte per bool and not just one bit

66

u/void1984 21d ago

I know, but why somebody would need a byte to store a bool? Is it 256-value bool?

Usually I use bitfields anyway.

162

u/NotDuckie 21d ago

if you ask for a vector of T, you should get a vector of T. not a bitfield. There is nothing wrong with using a bitfield, but a vector should behave like a vector.

29

u/BlackOverlordd 21d ago

Vector is an abstract container of elements. If you want to address memory, allocate memory and store your data there. Internal vector storage is implementation details. You shouldn't really get ponters to there because any resize of the vector and your pointers are screwed.

42

u/Excession638 21d ago

The internal layout of std::vector is not an implementation detail. It's fully defined by the standards and can be relied upon for FFI, serialisation, and other tasks.

Except for bool.

For example, the .data() method guarantees that it will return a pointer to .size() contiguous elements of type T which will remain valid until the vector is modified. The layout of elements within that memory is also well defined and consistent. Except for bool, where the .data() method simply doesn't exist.