有虚函数的字节对齐问题 困惑??

zxpsunshine 2005-10-12 11:44:16
class Base
{
public:
char c3;
double d;
char c4;
Base(){}
virtual ~Base(){}
};

void main()
{
cout << "alignment of Base = " << __alignof(Base) << endl;
cout << "offset of Base.c3 = " << offsetof(Base, c3) << endl;
cout << "offset of Base.d = " << offsetof(Base, d) << endl;
cout << "offset of Base.c4 = " << offsetof(Base, c4) << endl;
cout << "sizeof(Base) = " << sizeof(Base) << endl;
return;
}

为什么c3的偏移是8而不是4呢?Base类的开始部分应该是vptr,其大小应该是四个字节,这样的话c3原本的偏移应该是0 + 4 = 4,而c3的alignment应该是1,为什么还要对齐到8呢?困惑啊
...全文
165 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
runall 2005-10-12
  • 打赏
  • 举报
回复
可能就是按8字节对齐
class Base
{
public:
char c3;
double d;
// char c4;
Base(){}
~Base(){}
};

void main()
{
cout << "alignment of Base = " << __alignof(Base) << endl;
cout << "offset of Base.c3 = " << offsetof(Base, c3) << endl;
cout << "offset of Base.d = " << offsetof(Base, d) << endl;
// cout << "offset of Base.c4 = " << offsetof(Base, c4) << endl;
cout << "sizeof(Base) = " << sizeof(Base) << endl;
return;
}
LDD123 2005-10-12
  • 打赏
  • 举报
回复
关注
struggle813 2005-10-12
  • 打赏
  • 举报
回复
cout << "alignment of Base = " << __alignof(Base) << endl;就是当前的对齐字节数,与你的编译设置有关.
Microsoft Specific
__declspec(align(#)) declarator
Use __declspec(align(#)) to precisely control the alignment of global data. By aligning frequently used data to the cache line size of a specific processor, you improve cache performance. For example, if you define a structure whose size is less than 32 bytes, you may want to align it to 32 bytes to ensure that objects of that structure type are efficiently cached.

# is the alignment value. Valid entries are powers of two from 1 to 8192 (bytes). For example, 2, 4, 8, 16, 32, or 64. declarator is the global data that you are declaring as aligned.

You can use __declspec(align( # )) when you define a struct, union, or class, or when you declare a variable.

Without __declspec(align( # )), Visual C++ aligns data on natural boundaries based on the size of the data, for example 4-byte integers on 4-byte boundaries, and 8-byte doubles on 8-byte boundaries. Data in classes or structures is aligned within the class or structure at the minimum of its natural alignment and the current packing setting (from #pragma pack or the /Zp compiler option).

You cannot specify alignment for stack variables.

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧