问题
Can we use #pragma pack() before a class?
What is the significance of pragma here? I know it is used for giving information to compiler regarding implementation, but what if we use it with a class?
回答1:
It has the exact same effect on a class as it does on a struct, affecting the alignment of data members.
Actually using it on a class is very unusual and almost always a mistake. The layout of a C++ class object is heavily implementation defined. A C++ compiler usually makes an effort to optimize that layout, dropping the v-table pointer when it can. And potentially adding one when the class uses multiple inheritance. So a minor change to the class declaration, like making a method virtual or adding a base class can significantly alter the object layout. This will then of course break the code that depends on that pragma. Like an object serialized to a binary file won't deserialize properly anymore. In general a bad practice too but happens all the time anyway. Don't use it.
来源:https://stackoverflow.com/questions/16807632/use-of-pragma-pack-on-a-class