Trying to use std::vector<bool>
I have a compiler error that is very surprising to me.
In short taking the address of an element of a std::vector<unsigned char>
and assigning it to a unsigned char
pointer:
std::vector<unsigned char> test(10);
unsigned char *pb = &test[0];
works perfectly well, while trying to do the same thing with a std::vector<bool>
results in a compiler error:
int main() {
std::vector<bool> test(10);
bool *pb = &test[0]; // line 4, compile error
return 0;
}
On Visual Studio, it says something like:
std::vector bool cannot convert std::_Vb_reference<_Alloc> * to bool *
while codepad (see example at http://codepad.org/vaiN3iEq) says:
cc1plus: warnings being treated as errors
In function 'int main()':
Line 4: warning: taking address of temporary
Line 4: error: cannot convert '__gnu_norm::_Bit_reference*' to 'bool*' in initialization
compilation terminated due to -Wfatal-errors.
I thought both bool
and unsigned char
were internally the same (just a 1 byte type, with some compiler stuffs to enforce bool
to allow only true/false values). But I was not expecting such problem! Any idea why?!
Note that I know of bitsets and am not interested in using them here.
Yes, bool
and unsigned char
typically take the same amount of memory on their own, but that does not make vector<bool>
and vector<unsigned char>
the same!
vector<bool>
is given very, very special treatment by the standard in order to pack elements as close as possible (which someone in the 1990s thought would be clever, since a bool
has one of only two states), and the result is what you've seen: its elements are non-addressable.
Avoid!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With