【问题标题】:Layout of an object对象的布局
【发布时间】:2012-08-20 16:58:56
【问题描述】:

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

#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:我知道这是特定于实现的。我想知道该实现是如何完成的:)。这是因为我想访问私有成员,所以试图理解对象布局!!!

【问题讨论】:

  • 使对象非私有?试图“击败编译器”会给你带来麻烦。如果它不是您的源代码,那么它们是私有的可能是有原因的!

标签: c++ object object-layout


【解决方案1】:

整数 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
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-09
    • 2019-01-06
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2011-01-16
    • 2014-03-07
    • 2013-08-07
    相关资源
    最近更新 更多