r/learnprogramming • u/Vericus • Feb 29 '12
[C++] Why is vector<bool> bad?
I was thinking of creating a matrix of boolean values and I thought of vector<vector<bool>>, but after reading about vector<bool>, many websites have said it's something that should be avoided and it's bad programming.
Can someone explain to me why? I never really found a concrete explanation for why vector<bool> was bad. It only uses one bit which is 8 times smaller than char, shouldn't that mean its much better than using any other method of creating a matrix of bools in terms of size?
6
Upvotes
View all comments
Show parent comment
2
u/Rhomboid Feb 29 '12
It uses the space saving optimization of using one bit to represent each bool, and it packs them like a bitfield, storing multiple items at each memory address. But the return type of
operator[]for a vector of typeTis supposed to be a reference, i.e.T &. It's impossible to create a pointer or reference to an individual bit; memory doesn't work that way, it only has granularity of a byte.To get around that, the
operator[]doesn't return a reference to a bool value but to some proxy object that acts in its place, getting and setting the correct bit when accessed. This mucks with the assumptions of the rest of the STL, which expect to be able to get pointers/references to T.