From http://www.cplusplus.com/reference/stl/bitset/:
Because no such small elemental type exists in most C++ environments, the individual elements are accessed as special references which mimic
boolelements.
How, exactly, does this bit reference work?
The only way I could think of would be to use a static array of chars, but then each instance would need to store its index in the array. Since each reference instance would have at least the size of a size_t, that would destroy the compactness of the bitset. Additionally, resizing may be slow, and bit manipulation is expected to be fast.
I think you are confusing two things.
The
bitsetclass stores the bits in a compact representations, e.g. in achararray, typically 8 bits perchar(but YMMV on “exotic” platforms).The
bitset::referenceclass is provided to allow users of thebitsetclass to have reference-like objects to the bits stored in abitset.Because regular pointers and references don’t have enough granularity to point to the single bits stored in the
bitset(their minimum granularity is thechar), such class mimics the semantic of a reference to fake reference-like lvalue operations on the bits. This is needed, in particular, to allow the value returned byoperator[]to work “normally” as an lvalue (and it probably costitutes 99% of its “normal” use). In this case it can be seen as a “proxy-object”.This behavior is achieved by overloading the assignment operator and the conversion-to-
booloperator; thebitset::referenceclass will probably encapsulate a reference to the parentbitsetobject and the offset (bytes+bit) of the referenced bit, that are used by such operators to retrieve and store the value of the bit.—EDIT—
Actually, the g++ implementation makes the
bitset::referencestore directly a pointer to the memory word in which the byte is stored, and the bit number in such word. This however is just an implementation detail to boost its performance.By the way, in the library sources I found a very compact but clear explanation of what
bitset::referenceis and what it does: