1
votes

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?

1
It's implementation defined. - Jabberwocky
This question itself is a great demo of proper #pragma pack usage and syntax. Just what I was looking for on how to use #pragma pack! - Gabriel Staples
Keep in mind, in C++, a struct is just a class where all members default to public if not otherwise specified, and a class is just a class/struct where all members default to private unless otherwise specified, so it seems to me that more narrowly packing just the desired members within a class or struct, rather than the entire class or struct as you have done, would affect a class or struct identically. - Gabriel Staples

1 Answers

2
votes

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."