Home > Net >  How to deal when two objects share the same address?
How to deal when two objects share the same address?

Time:11-17

Background: I don't know a lot about memory location neither how zero size objects work, nor how to manipulate them.

Since a base class subobject of a standard layout class type with no non-static data member have zero size ( source 1 ), I expect that in the following code struct B has a zero size base-class subobject

struct A{};
struct B:A{};
int main(){A a; B b;}

Both a and bobjects have a size of 1 byte, but in the draft its said ( source_2 ):

The address of a non-bit-field subobject of zero size is the address of an unspecified byte of storage occupied by the complete object of that subobject.

So the address of the base-class subobject is the addres of an unspecified byte occupied by b, but it only has 1 byte, so b and its base-class subobject share the same address? If I didn't miss anything and the conclusion is right, how zero size subobjects are handled when "pointered" to?

CodePudding user response:

So the address of the base-class subobject is the addres of an unspecified byte occupied by b, but it only has 1 byte, so b and its base-class subobject share the same address?

Yes.

If I didn't miss anything and the conclusion is right, how zero size subobjects are handled when "pointered" to?

The value of the pointer is the address of the (sub-)object. Same as (sub-)objects of non-zero size.

  • Related