Search code examples
c++bit-manipulationbitset

Q: How bitset are inside?


The question is really simple (to ask), std::bitset<32> is the same thing as uint32_t for the memory? Or it's more like std::array<bool, 32> ?

I usually do something like:

uint32_t  index : 20;
uint32_t  magic : 12;

So it's the same as this code ?

std::bitset<20>  index;
std::bitset<12>  magic;

Solution

  • uint32_t  index : 20;
    uint32_t  magic : 12;
    

    So it's the same as this code ?

    std::bitset<20>  index;
    std::bitset<12>  magic;
    

    Absolutely not, and it's very important that you understand the difference.

    First, the internal representation of std::bitset<> is down the implementation.

    With that out of the way we should examine the difference between the two code snippets above.

    In c++ a bitfield is not a discrete object. This has important implications in multi-threaded code.

    This is because c++11 and greater guarantees that unprotected access from two threads to two discrete objects is safe, but access of the same non-const object by two more more threads is a data race unless protected by a mutex.

    In the above bitset code it would be correct to say:

    thread1: index = 10;

    thread2: auto x = magic;

    Because they are discrete objects and therefore guaranteed not to cause data races when accessed from different threads.

    In the bitfield code this would not be safe. The update of index would be a race with the reading of magic, and this is undefined behaviour.