c++ - 编译器如何为这个结构分配内存?

标签 c++ namespaces

<分区>

我在尝试使用命名空间和结构时遇到了问题。

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

当我将“命名空间二”的代码更改为以下内容时:

namespace Two
{
    struct Data
    {
        char val;
        bool boolean;
    };
}

Output :

functionOne()
The size of struct Data : 8
functionTwo()
The size of struct Data : 2

我无法弄清楚编译器如何为结构分配内存。提前致谢。

最佳答案

这里的问题很可能是由于对齐要求。如果我没记错的话,该结构是根据其成员的最大对齐要求对齐的。在您的结构的第一个版本中,您有 int;字符;。似乎在您的机器上 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

关于c++ - 编译器如何为这个结构分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17774276/

相关文章:

python - XPath 返回空列表(命名空间问题?)

c# - 将第 3 方 C++ DLL 引用到 VS 2013 项目中

c++ - 在销毁对象之前锁定对象的互斥体将释放内存或其他一些意外的

c++ - 如何在 Linux 上的 C++ 中包含 <atomic>?

c# - 命名空间和类具有相同的名称

c++ - 命名空间别名会影响大型代码库的构建时间吗? (C++)

c++ - 如何将图像保存在调整大小的 QLabel 中?

c++ - 类 - 从对象 vector 中删除特定对象

c# - 如何检查字符串是否是命名空间

c# - Parent - C# 中的 CChild 管理