c++c++11c++14memory-layout

Is bitset guaranteed contiguity?


Swift and easy question: is std::bitset guaranteed to be contiguous in memory?

I know it abides by CopyConstructible and CopyAssignable concepts, but is it also a ContiguousContainer (or something like that) like std::vector?

Apart from padding, I'd like to make bitwise operations on structures like this:

struct tmp
{
    std::bitset<32> b;
    unsigned int    c;
};

So the contiguity of b is quite important. Of course, this leads to knowing if std::bitset is a standard layout class, so that every bitwise operation works.


Solution

  • There is no such guarantee. std::bitset has, in my experience, an awkward interface, so I don't see much of the point of using it in undefined ways either.

    Just write your own bitset like class with the layout and storage guarantees you need.

    Personally, I'd enjoy it. And I don't find the bitset interface (especially construction/serialization/deserialization) particularly good, so I wouldn't even feel guilty. (I guess writing an efficient count, any, all and none is a bit of work, but everything else is trivial. And if you are writing assembly instructions/using SSE intrinstics, you might be able to match/exceed your compiler's implementation anyhow)