9

#pragma packVisual C++でのアラインメントの範囲は? API リファレンス https://msdn.microsoft.com/en-us/library/vstudio/2e70t5y1%28v=vs.120%29.aspx には次のように書かれています。

pack は、プラグマが表示された後の最初の構造体、共用体、またはクラスの宣言で有効になります

したがって、次のコードの結果として:

#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));
}

私は期待しました:

Size of the FirstExample is 5
Size of the SecondExample is 8

しかし、私は受け取った:

Size of the FirstExample is 5
Size of the SecondExample is 5

だからこそ、私は少し驚いており、あなたが提供できる説明に本当に感謝しています.

4

3 に答える 3

6

これは、プラグマが検出された後の最初の構造体、共用体、またはクラスの宣言で有効になり、最初に検出された #pragma pack(pop) または別の #pragma pack(push) がその pop カウンターパートまで続くまで続きます。

(通常、プッシュとポップはペアで行われます)

于 2015-06-24T19:14:16.830 に答える