Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

taking address of temporary while accessing address of a element in vector<bool>

Tags:

c++

I am getting the warning only while accessing address of element in vector of bool. For vector of other data types like int i don't get any warning.

eg

vector<bool> boolVect;
boolVect.push_back(false);
if (boolVect.size() > 0) {
    cout << &boolVect[0] << endl;
}   

I get warning "taking address of temporary" at statement "cout << &boolVect[0] << endl;"
Can someone please clarify?

like image 784
Rahul Avatar asked Nov 30 '11 10:11

Rahul


2 Answers

std::vector<bool> is broken (see e.g. http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=98 or Alternative to vector<bool>). It's a specialization of std::vector<T>, but the individual elements are stored as packed bits. Therefore, you can't take the address of an individual element. Therefore, it's really annoying.

like image 187
Oliver Charlesworth Avatar answered Nov 10 '22 04:11

Oliver Charlesworth


A vector<bool> is a template specialization of the standard vector. In a normal implementation it saves space, that every bool only takes one bit. For convenience you get a temporary object as a reference for your single bit which you otherwise could not address.

like image 25
Constantinius Avatar answered Nov 10 '22 03:11

Constantinius