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, its operator[]
, and its other member functions return proxy objects that provide access to the elements without requiring actual bool
objects to be stored.
If you need to be able to access individual elements, consider using a std::vector<char>
or defining a bool
-like enumeration backed by a char
(or a signed char
or unsigned char
, if you care about signedness).
vector<bool> is a special class template specialization for the bool type.
This specialization is provided to optimize for space allocation: eight bool elements are combined to one byte and each bool element occupies only one bit.
Reference to one bit in certain one byte is not allowed.
So the function could not return the reference to the a bool type in vector<bool>.
Someone also thinks vector<bool> is not a container.
You can use deque<bool> instead.
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