在类上使用#pragma pack [英] Use of #pragma pack on a class

查看:129
本文介绍了在类上使用#pragma pack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在类之前使用#pragma pack()吗?

Can we use #pragma pack() before a class?

pragma在这里的意义是什么?我知道它用于向编译器提供有关实现的信息,但是如果我们使用它与一个类怎么办?

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?

推荐答案

对类在结构上的精确效果相同,影响数据成员的对齐。

It has the exact same effect on a class as it does on a struct, affecting the alignment of data members.

实际上在类上使用它是非常不寻常的,几乎总是一个错误。 C ++类对象的布局是严格实现定义的。 C ++编译器通常会努力优化该布局,在可能时删除v表指针。并且当类使用多继承时,可能添加一个。因此,类声明的一个小改动,比如创建一个方法 virtual 或添加一个基类可以显着改变对象布局。这当然会打破依赖于该pragma伪指令的代码。像一个对象序列化为二进制文件不会反序列化正确。一般来说,一个坏的做法,但也发生了所有的时间。不要使用它。

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.

这篇关于在类上使用#pragma pack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆