gpt4 book ai didi

c++ - 数据成员地址是否位于 (this) 和 (this+1) 之间?

转载 作者:可可西里 更新时间:2023-11-01 18:27:49 27 4
gpt4 key购买 nike

假设我们在一个成员函数中有如下两个不等式

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

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

它们能保证是真的吗?(在我检查过的一些情况下,它们似乎是正确的。)

编辑:我漏掉了符号,现在它是不等式的正确形式。

最佳答案

来自 CPP 标准草案 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).

综上所述,我们可以说第一个等式至少适用于普通可复制对象。

同样来自网上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)

因此,如果您的data_member 不是 指针并且没有单独分配内存,那么您发布的方程式仍然有效对于至少平凡可复制的对象。

关于c++ - 数据成员地址是否位于 (this) 和 (this+1) 之间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53704690/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com