2

オブジェクトのレイアウトを理解したい。そのため、メンバー変数の順序を変えて実行しました。すべてが期待どおりに行われました。次のシーケンスを期待してください。

#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を削除すると、期待されるinput(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:これは実装固有のものだと思います。その実装がどのように行われたか知りたいです:)。プライベートメンバーにアクセスしたいので、これが思い浮かびましたので、オブジェクトのレイアウトを理解しようとしています!!!

4

1 に答える 1

3

整数m_a sizeof(Test1)は 8 でm_a、4 バイト境界に合わせます。int がなければ、 th のサイズだけ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
};
于 2012-08-25T10:26:21.357 に答える