gpt4 book ai didi

c++ - 对象的布局

转载 作者:搜寻专家 更新时间:2023-10-31 01:52:46 24 4
gpt4 key购买 nike

我想了解一个对象的布局。所以我执行了不同顺序的成员变量。一切如期而至,期待接下来的顺序。

#include <iostream>

using namespace std;
class Test1
{
public:
int m_a;
char m_b;
};


class Test
{
public:
int m_b;
Test1 m_t;
char m_g;
char m_c;
char m_d;
int m_e;
};

int main()
{
Test t;
cout<<(int*)(&t.m_b)<<endl;
cout<<(int*)(&t.m_t.m_a)<<endl;
cout<<(int*)(&t.m_t.m_b)<<endl;
cout<<(int*)(&t.m_c)<<endl;
cout<<(int*)(&t.m_d)<<endl;
cout<<(int*)(&t.m_e)<<endl;
cout<<sizeof(t)<<endl;
}

输出:

0xbfebbd6c
0xbfebbd70
0xbfebbd74
0xbfebbd79
0xbfebbd7a
0xbfebbd7c
20

如我所料 16.

但是如果我从 Test1 中删除 m_a,它会给出预期的输入 (12)。

#include <iostream>

using namespace std;
class Test1
{
public:
char m_b;
};


class Test
{
public:
int m_b;
Test1 m_t;
char m_g;
char m_c;
char m_d;
int m_e;
};

int main()
{
Test t;
cout<<(int*)(&t.m_b)<<endl;
cout<<(int*)(&t.m_t.m_b)<<endl;
cout<<(int*)(&t.m_c)<<endl;
cout<<(int*)(&t.m_d)<<endl;
cout<<(int*)(&t.m_e)<<endl;
cout<<sizeof(t)<<endl;
}

输出:

0xbf82e674
0xbf82e678
0xbf82e67a
0xbf82e67b
0xbf82e67c
12

如果我删除与 4 位边界完全对齐的整数,为什么会有 8 个字节的差异?

PS:我知道这是特定于实现的。我想知道该实现是如何完成的:)。这是因为我想访问私有(private)成员,所以试图了解对象布局!!!

最佳答案

整数 m_a sizeof(Test1) 为 8 以将 m_a 对齐到 4 字节边界。如果没有 int,它只有 char 的大小。

class Test
{
public:
int m_b; // 4
Test1 m_t; // 12
char m_g; // 13
char m_c; // 14
char m_d; // 15

int m_e; // 20
};

关于c++ - 对象的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12121084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com