开发者

Memory layout question

Do these two structs have the same memory layout? (C++)

struct A
{
   int x;
开发者_JS百科   char y;
   double z;
};

struct B
{
   A a;
};

Further can I access x, y, z members if I manually cast an object of this to an A?

struct C
{
   A a;
   int b;
};

Thanks in advance.

EDIT:

What if they were classes instead of structs?


Yes and yes. The latter is commonly used for emulating OO inheritance in C.


You can verify this yourself by checking field offsets relative to the start of an instance of each.

A aObj;
B bObj;
C cObj;

int xOffset1 = &aObj.x - &aObj;
int xOffset2 = &bObj.a.x - &bObj;

ASSERT(xOffset1 == xOffset2);

and so on


$9.2/16- "Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types (3.9)."

So the answer is 'yes'


Yes, that'll work. Depending on compiler structure packing settings, it may not work with members other than the first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜