总是相同的效果#pragma pack(16)和#pragma pack(8)? [英] Always same effect of #pragma pack(16) and #pragma pack(8)?

查看:663
本文介绍了总是相同的效果#pragma pack(16)和#pragma pack(8)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 #pragma pack(n) 。以下面的示例为例:

  #include< iostream> 
using namespace std;

#pragma pack(8)//或(16)

struct A
{
int a;
char b
char c;
char d;
char e;
char f;
double g;
};
int main()
{
cout<< sizeof(A)< endl;

return 0;
}

两者都会打印 24 #pragma pack(8) #pragma pack(16)我可以理解 n = 8 的结果与数据对齐,我的理解如下:

 字节数:| 1 2 3 4 | 5 | 6 | 7 | 8 | 9 | 10 11 12 13 14 15 16 | 17 18 19 20 21 22 23 24 | 
数据:| a | b | c | d | e | f | padding | g |

但我不明白为什么结果还是 24 n = 16 。我也试过其他例子,他们似乎给出相同的结果 n = 8 n = 16 。有人可以解释为什么吗?数据成员是否与 n = 8



相同?PS:在VS2010中在Win-x64下测试。

解决方案

从您链接到的页面:


成员的对齐方式将在边界上,该边界是
的n倍或成员大小的倍数,以较小的
为准。


对于每个成员,它采用成员的最佳对齐方式和包值之间的最小对齐方式。无论 pack(8) pack(16),您的示例中的成员都对齐完全相同,



如果您有一个需要16字节对齐的成员,例如 __ m128 ,您将能够找到不同的结果。


I am trying to align data members by using #pragma pack (n). Take the following as an example:

#include <iostream>
using namespace std;

#pragma pack(8) // or (16)

struct A
{
    int a;
    char b;
    char c;
    char d;
    char e;
    char f;
    double g;
};
int main()
{
    cout << sizeof(A) << endl;

    return 0;
}

Both will print 24 for #pragma pack(8) and #pragma pack(16). I can understand the result for n=8 with the data alignment, of my understanding, as follows:

Bytes: |1 2 3 4|5|6|7|8|9|10 11 12 13 14 15 16|17 18 19 20 21 22 23 24|
 Data: |a      |b|c|d|e|f|padding             |g                      |

But I cannot understand why the result is still 24 for n=16. I also tried other examples, all of them seems to give same result for n=8 and n=16. Can someone explain why? Are the data members aligned the same way as n=8?

P.S.: Tested in VS2010 under Win-x64.

解决方案

From the page you linked to:

The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.

For each member it takes the minimum alignment, between the member's optimal alignment and the pack value. The members in your example are aligned exactly the same regardless of pack(8) and pack(16) because the optimal alignment of the types are all less than 16.

If you had a member that required 16-byte alignment, such as __m128, you would be able to find different results.

这篇关于总是相同的效果#pragma pack(16)和#pragma pack(8)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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