|
|
> On Tue, 10 Mar 2009 21:08:05 +0100, Orchid XP v8 <voi### [at] devnull> wrote:
> > ...because C++ "bool" is actually some mannar of integer?
The main problem is that you can't have a pointer pointing to an
individual bit. The smallest element to which a pointer can point is
a byte.
However, in a std::vector<bool> you have 8 bools per byte, and you can't
create a pointer (or reference) which will point to one of them. This
makes std::vector<bool> behave inconsistently compared to a std::vector
of any other type.
You can index a std::vector<bool> in the regular way, and you can even
assign values to these indexed elements. In other words, you can do this:
std::vector<bool> boolVec(100, false);
boolVec[50] = true; // Works ok
However, since operator[] cannot return a true reference to the indexed
bool (because there can't be a reference to an individual bit), what it
returns is a proxy object which behaves like if it was a reference to the
individual bit. Thus it almost looks like std::vector<bool> behaves like
any other vector.
However, since operator[] for bool vectors does not return a reference
of type bool, you can't do something like this:
bool& boolRef = boolVec[50];
That will simply fail. The same would work for any type other than bool.
References and pointers to vector elements are used quite a lot in
practical C++, so this makes std::vector<bool> inconsistent and less
usable than it could be.
Since it's rare in practice that one would need a huge std::vector<bool>
(if what you really need is a huge bitset, then boost::dynamic_bitset is
by far a better choice, as it's more versatile and efficient), it can be
argued that making std::vector<bool> special was a design mistake.
It has been suggested that std::vector<bool> would instead allocate
one byte per element because bytes can be addressed, and this would make
it consistent. It would probably also make it more efficient speedwise.
Fredrik Eriksson <fe79}--at--{yahoo}--dot--{com> wrote:
> No, because std::vector<bool> is specialised in such a way that:
> 1 - It is not a container (not as the C++ standard defines them)
I'm not really sure what you mean by that.
std::vector<bool> works mostly like any other container. The only thing
it cannot do is give you an address to an individual element. Too bad that's
a cumbersome limitation in some cases.
--
- Warp
Post a reply to this message
|
|