7

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?

Rahul
  • 257
  • 1
  • 4
  • 11

2 Answers2

15

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.

Community
  • 1
  • 1
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • I have a template class. It uses "vector vect", and access address(&vect[i]). I get compile time warning here for T=bool. How can I get rid of this warning if for T=bool, the address is not accessed? – Rahul Dec 01 '11 at 13:14
  • @Rahul (Long time since you posted, but still...) Can you do a template specialization for bool? You could provide a different implementation for bool that avoids taking the address of an element. – Daryn Dec 14 '12 at 19:36
4

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.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Constantinius
  • 34,183
  • 8
  • 77
  • 85