即使向其添加新成员后,结构大小也保持不变

Ven*_*esh 0 c++ string struct

何时只是执行

cout << sizeof(string);
Run Code Online (Sandbox Code Playgroud)

我得到8作为答案.

现在我有一个结构

typedef struct {
    int a;
    string str;
} myType;
Run Code Online (Sandbox Code Playgroud)

而我正在执行

cout << sizeof(myType);
Run Code Online (Sandbox Code Playgroud)

我得到16作为答案.

现在我改变了我的结构

typedef struct {
    int a, b;
    string str;
} myType;
Run Code Online (Sandbox Code Playgroud)

而我正在执行

cout << sizeof(myType);
Run Code Online (Sandbox Code Playgroud)

我得到16作为答案!怎么样?怎么了?

Ale*_*exD 7

也许填充正在发生.例如,sizeof(int)可以是4个字节,并且a为了数据对齐,编译器可以添加4个字节.布局可能是这样的:

typedef struct {
    int a;      // 4 bytes
                // 4 bytes for padding
    string str; // 8 bytes
} myType;

typedef struct {
    int a;      // 4 bytes
    int b;      // 4 bytes
    string str; // 8 bytes
} myType;
Run Code Online (Sandbox Code Playgroud)