Use of #pragma pack on a class

2019-07-03 10:53发布

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?

标签: c++ class pragma
1条回答
别忘想泡老子
2楼-- · 2019-07-03 11:26

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.

查看更多
登录 后发表回答