Search code examples
c++classmemory-alignmentpacking

C++ Class packing / member alignment


I know structure packing is a common thing in C++ programming (at least on low memory systems). But what about classes. I know it works because I tried it

#include <iostream>

#pragma pack(push, 1)
class Test_Packed {
    uint8_t t;
    uint32_t test;
};
#pragma pack(pop)

class Test_Unpacked {
    uint8_t t;
    uint32_t test;
};

int main() {
    std::cout<<sizeof(Test_Packed) << " / " << sizeof(Test_Unpacked)<<std::endl;
    return 0;
}

Which correctly outputs "5 / 8".

Can I assume this to be the case on all conforming Compilers, or is this implementation defined?

I know that adding virtual members (and thus needing a vtable) will add additional data in the front. What can be other reasons for this to fail?

Can this cause any problems except for poor performance on some platforms?


Solution

  • The documentation for #pragma states:

    Implementation defined behavior is controlled by #pragma directive.

    So the effect, if any, of #pragma pack(push, 1) and #pragma pack(pop) is completely "implementation defined."