In the following code:
class SomeClass {
vector<int> i;
vector<bool> b;
public:
int& geti() {return i[0];}
bool& getb() {return b[0];}
};
If you comment out getb(), the code compiles fine. Apparently there’s no problem returning a reference to an int that’s stored in a vector, but you can’t do it with a bool.
Why is this?
std::vector<bool>is “special.” It stores its elements as a bit array, meaning that the elements are not individually addressable and you cannot obtain a reference to an element.std::vector<bool>iterators, itsoperator[], and its other member functions return proxy objects that provide access to the elements without requiring actualboolobjects to be stored.If you need to be able to access individual elements, consider using a
std::vector<char>or defining abool-like enumeration backed by achar(or asigned charorunsigned char, if you care about signedness).