r/ProgrammerHumor • • 12d ago

Meme cppAndItsVectorBooleans

Post image
3.4k Upvotes

214 comments sorted by

View all comments

Show parent comment

17

u/Own_Lake_276 12d ago

The problem is that it’s inconsistent and leads to unexpected bugs. If I want to use a bitmask because I really care about memory then I’ll use a bitmask

0

u/Mountain-Ox 12d ago

What kind of bugs? Nothing would be inspecting the memory values of the vector directly.

The problem with a bit mask is it can only work up to 64 bits afaik. What if you have hundreds of bools that you need to manage?

7

u/telionn 12d ago

Try grabbing a pointer-to-bool from std::vector<bool> and see what happens.

Vector<bool> isn't that bad in a vacuum, honestly, since you can just avoid it. The real problem is when you write `template<typename T> class MyDataStruct { std::vector<T> innerStorage }` and then create a `MyDataStruct<bool>` and it unexpectedly falls apart. Now you have to build a pointless type trait system to remap bool onto uint8_t or something.

4

u/narrill 12d ago

What if you have hundreds of bools that you need to manage?

Then you have a separate type that works the way vector<bool> does now, allowing vector<bool> to, you know, be a vector.

1

u/Bitter_Ad3906 11d ago

Problem of wrong implementation of bool, not for what use case for it. If you need separate implementation for it, then it should be excluded from start. Assume you have sequence of simple numbers and in that list got 12, 12 also number but wrong one. It’s same for std::vector<bool> differ from rest.

1

u/narrill 10d ago

I don't know what this comment is trying to say. Dynamic bool collections with and without bit packing are both legitimate use cases, and of the two, vector<bool> should obviously be the latter because that is how vector already works. If you want a tightly packed collection that breaks vector's invariants, it should be its own type and not a specialization of vector.

I'm not sure what "wrong implementation of bool" is meant to mean either. A bool in C++ is not a single bit, definitionally.

1

u/Bitter_Ad3906 9d ago

Just when implement class need follow rules to all, not make 1 out of rest. Mem usage be good, but for it can be new one like memCompactVector<bool> etc.