I’m making a vector<bool> implementation. I save an unsigned int and use bitwise operations to have a vector of true and false. My problem is this; I can access individual bits by operator[], but how do I get a reference to such a bit so I can write
Vector<bool> v(5, true);
v[3] = false;
Somewhere I heard that you shouldn’t do references/pointers to individual bits. A summary of the code, that works for retrieving bit value:
...
unsigned int arr; // Store bits as unsigned int
unsigned int size_vec; // The size of "bool vector"
...
bool& Vector<bool>::operator[](unsigned int i) {
if (i>=vec_size || i<0) {
throw out_of_range("Vector<bool>::operator[]");
}
int index = 1 << (i-1);
bool n = false;
if (index & arr) {
n=true;
}
return n;
};
So, how can you return some sort of reference making it possible to change the individual bits?
You need to define a proxy object with the appropriate operator overloads so that it acts like
bool&but addresses individual bits. This is whatstd::vector<bool>does.Something like this:
Generally I would recommend avoiding things like this that rely on sneaky implicit conversions in C++ because it really messes with your intuition, and it doesn’t play nicely with things like
autoanddecltypein C++11.