r/ProgrammerHumor • • 11d ago

Meme cppAndItsVectorBooleans

Post image
3.4k Upvotes

214 comments sorted by

View all comments

Show parent comment

1

u/Carbon_Cotton 10d ago

Because std::vector<T> has interface all of its implementations must follow - stuff like iteration, dereference

And while storing booleans as bits in std::vector<bool> shrinks the space usage by nearly 90%, it also means it cannot fully implement the std:vector interface.

Good example is reference - in other vectors, you can take reference to one of its items. You can then use this reference to work with item directly.

auto vec = std::vector<int>();
vec.push_back(10);

// this will obtain reference to 0th item    
auto& val = vec[0];
val = 15;

// this will print '15'    
std::cout << vec[0] <<std::endl;

This is IMPOSSIBLE with std::vector<bool> because there are no bools inside to reference - and referencing bits is impossible as well.

Instead, it will return weird proxy object that is trying its best to pretend it is bool reference. But it cannot ddo everything - and that breaks interface