填充和对齐 [英] Padding and alignment

查看:86
本文介绍了填充和对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我曾期望我的C ++编译器在类和结构中添加填充

将字段与其自然对齐边界。这似乎不是真的。


$ cat align.cxx

#include< cstdio>

struct foo

{

virtual void f()const {}

long long x;

};

int main()

{

foo bar;

printf("%p%p \ n",(void) *)& bar,(void *)& bar.x);

返回0;

}


$ ./a.out

0xbfd9da00 0xbfd9da04


在我的平台上(x86 Linux g ++)long long是64位宽。

(我想前4个字节存储了v指针。)

为什么编译器没有添加填充以将x对齐到64位边界?


问候。

Hello everyone,

I had expected my C++ compiler to add padding within classes and structs
to align fields to their "natural" boundary. This seems not to be true.

$ cat align.cxx
#include <cstdio>
struct foo
{
virtual void f() const { }
long long x;
};
int main()
{
foo bar;
printf("%p %p\n", (void *)&bar, (void *)&bar.x);
return 0;
}

$ ./a.out
0xbfd9da00 0xbfd9da04

On my platform (x86 Linux g++) long long is 64-bits wide.
(I suppose the first 4 bytes store the v-pointer.)
Why didn''t the compiler add padding to align x to a 64-bit boundary?

Regards.

推荐答案

cat align.cxx

#include< cstdio>

struct foo

{

virtual void f()const {}

long long x;

};

int main()

{

foo bar;

printf("%p%p \\\
&q uot;,(void *)& bar,(void *)& bar.x);

返回0;

}

cat align.cxx
#include <cstdio>
struct foo
{
virtual void f() const { }
long long x;
};
int main()
{
foo bar;
printf("%p %p\n", (void *)&bar, (void *)&bar.x);
return 0;
}


./ a.out

0xbfd9da00 0xbfd9da04


在我的平台上(x86 Linux g ++)long long是64 - 比特宽。

(我想前4个字节存储了v指针。)

为什么编译器没有添加填充以将x对齐到64-位边界?


问候。
./a.out
0xbfd9da00 0xbfd9da04

On my platform (x86 Linux g++) long long is 64-bits wide.
(I suppose the first 4 bytes store the v-pointer.)
Why didn''t the compiler add padding to align x to a 64-bit boundary?

Regards.


Spoon写道:
Spoon wrote:

大家好,


我原本期望我的C ++编译器在类和结构中添加填充

将字段与其自然对齐边界。这似乎不是真的。

Hello everyone,

I had expected my C++ compiler to add padding within classes and structs
to align fields to their "natural" boundary. This seems not to be true.


这篇关于填充和对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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