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

标签 c++ language-lawyer

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

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/

相关文章:

c++ - 错误 C244 '{' : missing function header (old-style formal list?) Visual C++

c++ - shared_ptr<void> t(new char[num]) 意味着内存泄漏?

c++ - 在嵌套名称说明符中使用 simple-template-id 是否明确表示类模板特化?

c++ - 为什么将值初始化指定为不调用平凡的默认构造函数?

perl - "our"或 "use vars"中有什么魔力满足 "use strict qw(vars)"?

c++ - 检查是否存在全局(/命名空间)函数/对象声明

c++ - Pybind11:如何为结构成员变量分配默认值?

C++ 类函数调用 fortran 子例程

c++ - vector 构造函数的另一个违反直觉的行为

c++ - 这是 "elision failure"语言强制要求的吗?