r/ProgrammerHumor • • 10d ago

Meme cppAndItsVectorBooleans

Post image
3.4k Upvotes

214 comments sorted by

View all comments

Show parent comment

84

u/Semper_5olus 10d ago

Oh. So a bool is, for whatever reason, a different size if it's in a vector.

And that makes generic functions hard to write without checking for this specific case.

I didn't know that.

That is annoying.

64

u/bwmat 10d ago

The reason is that the people working on that part of the spec felt clever that day

But not clever enough to realize they should have specified it as std::dynamic_bitset (or something like that) instead

53

u/KaMaFour 10d ago

Programmer feeling clever should be a massive alarm bell for everyone

2

u/Interesting-Crab-693 8d ago

I'll remember that in my object oriented programing class next year!

16

u/pyxlmedia 10d ago

It's Not a vector nor does it store bools.

10

u/cinnamonjune 10d ago

What's worse is that the spec says that all vector<T> must return a T& if you do an operator[] on them, but of course vector<bool> can't do this because there are no bools to reference, so the solution they came up with was to say that operator[] on vector<bool> returns a vector<bool>::reference which is an internal class that implicitly decays to bool.

This means that you can do `my_vec[0] = true;`, and you can do `bool b = my_vec[0];`, but if you do `auto b = my_vec[0];` then things go horribly wrong because the type of `b` is not `bool` but instead becomes `vector<bool>::reference`.

1

u/SubstituteCS 10d ago

std::vector<bool> stores values using bits to shave off space.

In a vacuum this makes a lot of sense as 8 bools only take 1 byte instead of 8 bytes.

In practice, this causes a lot of headaches down the line and can easily lead to problems if someone isn’t aware of this specific nuance.

std::vector<T> is essentially an List<T> if you know C#