Visual Studio中pragma pack指令的范围

rgb*_*rgb 8 c++ preprocessor-directive visual-studio-2013 pragma-pack

#pragma packVisual C++中对齐的范围是什么?API参考 https://msdn.microsoft.com/en-us/library/vstudio/2e70t5y1%28v=vs.120%29.aspx 说:

在看到pragma之后,pack在第一个struct,union或class声明生效

因此,以下代码的结果是:

#include <iostream>

#pragma pack(push, 1)

struct FirstExample
{
   int intVar;   // 4 bytes
   char charVar; // 1 byte
};

struct SecondExample
{
   int intVar;   // 4 bytes
   char charVar; // 1 byte
};


void main()
{
   printf("Size of the FirstExample is %d\n", sizeof(FirstExample));
   printf("Size of the SecondExample is %d\n", sizeof(SecondExample));
}
Run Code Online (Sandbox Code Playgroud)

我曾预料到:

Size of the FirstExample is 5
Size of the SecondExample is 8
Run Code Online (Sandbox Code Playgroud)

但我收到了:

Size of the FirstExample is 5
Size of the SecondExample is 5
Run Code Online (Sandbox Code Playgroud)

这就是为什么我有点惊讶,我真的很感激你能提供的任何解释.

AnT*_*AnT 6

仅仅因为它"在第一个结构上生效"并不意味着它的效果仅限于第一个结构.#pragma pack以预处理器指令的典型方式工作:它从激活点"无限期"持续,忽略任何语言级范围,即其效果扩展到翻译单元的末尾(或直到被另一个覆盖#pragma pack).


eng*_*010 5

它在看到pragma之后的第一个struct,union或class声明生效,并持续到第一次遇到#pragma pack(pop)或另一个#pragma pack(push),它持续到它的pop对应物.

(推和弹出通常成对出现)