我试图使用名称空间和结构并遇到问题.
C++
#include<iostream>
using namespace std;
namespace One
{
struct Data
{
int val;
char character;
};
}
namespace Two
{
struct Data
{
int val;
bool boolean;
};
}
void functionOne(void)
{
using namespace One;
cout << "functionOne()" << endl;
cout << "The size of struct Data : ";
cout << sizeof(Data) << endl;
}
void functionTwo(void)
{
using namespace Two;
cout << "functionTwo()" << endl;
cout << "The size of struct Data : ";
cout << sizeof(Data) << endl;
}
int main()
{
functionOne();
functionTwo();
}
Output
functionOne()
The size of struct Data : 8
functionTwo()
The size of struct Data : 8
Run Code Online (Sandbox Code Playgroud)
当我将'namespace Two'的代码更改为以下内容时:
namespace Two
{
struct Data
{
char val;
bool boolean;
};
}
Output :
functionOne()
The size of struct Data : 8
functionTwo()
The size of struct Data : 2
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚编译器如何为结构分配内存.提前致谢.
这里的问题很可能是由于对齐要求.如果我没有弄错的话,结构会根据其成员的最大对齐要求进行对齐.在您的结构的第一个版本中int; char;.在您的机器上,int似乎以4个字节对齐,因此编译器在char之后用额外的3个字节填充结构.在你只有的第二个版本中bool; char;,它们都是1个字节大小并且与1个字节(在你的机器上)对齐,因此编译器不需要填充任何内容,因此大小会回落到2.
我指定"在您的机器上",因为这可能因多种因素而异.
让我们制作一个漂亮的图表!
// One::Data (version 1)
0 4 5 7
[int (size 4), char (size 1), padding (size 3)][...]
// Because of alignment restrictions on int, this needs a padding of 3 bytes
// Two::Data (version 1)
0 4 5 7
[int (size 4), bool (size 1), padding (size 3)][...]
// Because of alignment restrictions on int, this needs a padding of 3 bytes
// One::Data (version 2), no change
// Two::Data (version 2)
0 1 2
[char (size 1), bool (size 1)][...]
// No alignment restrictions, therefore no padding is required
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
478 次 |
| 最近记录: |