Search code examples
c++c++11data-structuresbitset

Does std::bitset guarantee continious memory along with constant size in a structure (to avoid padding?)


if I have a structure:

struct foo
{
    int ibar;
    std::bitset<32> bsbar;
    float fbar;
};

does bitset guarantee there will be no padding bytes between ibar and bsbar and that the size of this struct will always be 12 (for use in memcpy operations)?


Solution

  • No, and you should first test and see what the answer may be:

    #include <iostream>
    #include <bitset>
    
    struct foo
    {
        int ibar;
        std::bitset<32> bsbar;
        float fbar;
    };
    
    int main(int argc, char const *argv[])
    {
        std::cout << sizeof(foo) << std::endl; // 24 on my machine (OS X 10.10 g++4.9.2 64 bit) 
    }