Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compiler error when pointing to an element of std::vector<bool>?

Tags:

c++

vector

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.

like image 597
nbonneel Avatar asked Jan 13 '14 23:01

nbonneel


1 Answers

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!

like image 196
Lightness Races in Orbit Avatar answered Sep 19 '22 12:09

Lightness Races in Orbit