1

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?

Thalhammer
  • 285
  • 3
  • 7
  • 2
    It's implementation defined. – Jabberwocky May 31 '17 at 14:10
  • 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 Sep 17 '20 at 15:59
  • 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 Sep 17 '20 at 16:02
  • See also: https://stackoverflow.com/questions/3318410/pragma-pack-effect – Gabriel Staples Sep 17 '20 at 21:15

1 Answers1

2

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

Ðаn
  • 10,934
  • 11
  • 59
  • 95