开发者

Does object store variables sequentially?

Could you use a pointer over class member variables to increment o开发者_如何学Gor decrement over any variable? Or why not?

For example, a struct or class

struct MyStruct {
   int x;
   int y;
   int z;
};

int main()
{
   MyStruct Obj;
   int *p = &Obj.x;

   cout << *p << endl;
   cout << p++ << endl;
   cout << p++ << endl;
}

I also noted the address of Obj and its variable is same.


x has the same address as Obj - this is guaranteed for structures without parent class or virtual members. x, y and z keep their ordering in memory, this is also guaranteed. There may be padding in between the struct members, this is implementation specific, so you cannot safely assume that your code is portable.


The variables could be of different sizes and there could be padding space between the different member variables, so simply incrementing a pointer like in your example will generally not work.


Normally it is stored sequentially and you can read about it here.. But I don't think it is possible to do what you suggest since it's not a universal fact.


Pretty sure that's not guaranteed behavior. That is, you might be able to find some examples where it happens, but I don't believe it's part of the ANSI standard so you results may vary.


It is not guaranteed behaviour; pointer arithmetic is only defined within an array object. According to the standard:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.


As others have said, you cannot do that reliably. What you can do is the following:

size_t offsets[] = {
    offsetof(MyStruct, x),
    offsetof(MyStruct, y),
    offsetof(MyStruct, z) };
size_t size_offset = sizeof offsets / sizeof offsets[0];

for (size_t i = 0; i < size_offsets; ++i)
    std::cout << *(&Obj + offsets[i]) << std::endl;

But as noted this is of very limited usefulness. If you find yourself doing this, you can be certain that there’s a serious design flaw in your program.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜