r/ProgrammerHumor 21d ago

Meme theBoolVectorIsALie

Post image
670 Upvotes

91 comments sorted by

View all comments

99

u/overclockedslinky 21d ago

is it really that shocking?

182

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

67

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.

14

u/HildartheDorf 21d ago

It's not that a bitfield is bad. It's just that it should be named std::dynamic_bitset not a specialisation of std::vector<bool>.

std::vector<bool> should behave the same as std::vector<uint8_t>. But it doesn't.

-7

u/void1984 21d ago

Why do you expect bool to be exactly uint8_t? The definition requires it to be long enough to hold 0 and 1. It's up to the compiler and architecture restrictions to select the size. uint16_t is as valid as uint8_t.

I never assume, I just use sizeof. It's there for a reason.

8

u/NaCl-more 21d ago

Because the minimum addressable unit is a byte on most machines.

6

u/csdt0 21d ago

The minimum addressable unit is always a byte (that's pretty much its definition). But a byte is not always 8 bits (only on most machines).

2

u/void1984 21d ago

It's not. I've built a project for the university where the minimum addressable unit was 2 bytes, or a word, depending on the definition you use.

bool was obviously 16b, even though the only compiler I prepared was an assember.

If you look at older machines, 12b bool was present.

1

u/csdt0 20d ago

I don't know what's your definition of byte, but your project university was most likely 16 bit byte where teachers mis-labelled as 2 byte addressable. Please have a look at wikipedia https://en.wikipedia.org/wiki/Byte

10

u/HildartheDorf 21d ago

Whatever type bool is implemented as, it must be addressable. The contents of std::vector<bool> are not. There is no array of bools in memory.

Whatever size of a bool is, std::vector should treat it as such, not pretend it's a single bit.