Home > Mobile >  For multiple instances of the same object, are member variables stored at the same offset?
For multiple instances of the same object, are member variables stored at the same offset?

Time:01-18

Say I have a struct Foo:

struct Foo
{
    char a;
    int b;
} Foo1, Foo2;

The compiler may insert padding so that Foo::a is stored at the start of the object's memory, and Foo::b is stored at an offset of 0x04 (say on a 32-bit system for example).

If I create multiple instances of this object Foo1 and Foo2, will they always have the same padding? Is there ever a case where Foo1::b is stored at offset 0x04 and Foo2::b is stored at offset 0x08 for example?

CodePudding user response:

For multiple instances of the same object, are member variables stored at the same offset?

Yes.

If I create multiple instances of this object Foo1 and Foo2, will they always have the same padding?

Yes.

Is there ever a case where Foo1::b is stored at offset 0x04 and Foo2::b is stored at offset 0x08 for example?

No.


This assumption holds only within the program. Compile the program on another system, and the offset can be different there.

CodePudding user response:

Consider offsetof:

#define offsetof(type, member) /*implementation-defined*/
           

The macro offsetof expands to an integral constant expression of type std::size_t, the value of which is the offset, in bytes, from the beginning of an object of specified type to its specified subobject, including padding if any.

offsetof relies on compiler internals, though the offset of a member of some type is a constant expression.

  •  Tags:  
  • Related