Do data member addresses lie between (this) and (this+1)?

  • A+
Category:Languages

Suppose that we have the following two inequalities inside a member function

this <=  (void *) &this->data_member 

and

&this->data_member < (void *) (this+1)  

Are they guaranteed to be true? (They seem to be true in a few cases that I checked.)

Edit: I missed ampersands, now it's the correct form of inequalities.

 


From CPP standard draft 4713:

6.6.2 Object model [intro.object]/7
An object of trivially copyable or standard-layout type (6.7) shall occupy contiguous bytes of storage.

12.2 Class members [class.mem]/18
Non-static data members of a (non-union) class with the same access control (Clause 14) are allocated so that later members have higher addresses within a class object.

12.2 Class members [class.mem]/25
If a standard-layout class object has any non-static data members, its address is the same as the address of its first non-static data member. Otherwise, its address is the same as the address of its first base class subobject (if any).

Taking all the above together, we can say the first equation holds for at least trivially copyable objects.

Also from the online cpp reference:

The result of comparing two pointers to objects (after conversions) is defined as follows:

1) If two pointers point to different elements of the same array, or to subobjects within different elements of the same array, the pointer to the element with the higher subscript compares greater. In other words, they results of comparing the pointers is the same as the result of comparing the indexes of the elements they point to.
2) If one pointer points to an element of an array, or to a subobject of the element of the array, and another pointer points one past the last element of the array, the latter pointer compares greater. Pointers to single objects are treated as pointers to arrays of one: &obj+1 compares greater than &obj (since C++17)

So if your data_member is not a pointer and has not been allocated memory separately, the equations you have posted hold good for at least trivially copyable objects.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: