Use of #pragma pack on a class

放肆的年华 提交于 2019-12-13 14:22:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!