#include <iostream> struct testingPointers { int i; float f; double d; } test; int main() { std::cout << &test << '\n' << &(test.i) << '\n' << &(test.f) << '\n' << &(test.d); }
输出是:
0x681110 0x681110 0x681114 0x681118
(显然,不同运行的确切值是不同的,但它们相对于彼此总是具有相同的位置).
我很困惑,因为第一个指针的值 – 测试的内存位置 – 与第二个指针(第一个测试字段)的值相同.这是否意味着对象没有真正唯一的内存地址,并且指向结构或类的指针只是指向其第一个字段?如果是这样,声明怎么样
a.b a->b a.b()
如果a实际上只是它的第一个字段,因此没有任何字段或方法?
解决方法
关于对象是否可以共享内存地址的标准的重要部分是§1.8/ 6:
Unless an object is a bit-field or a base class subobject of zero size,the address of that object is the address of the first byte it occupies. Two objects that are not bit-fields may have the same address if one is a subobject of the other,or if at least one is a base class subobject of zero size and they are of different types; otherwise,they shall have distinct addresses.
我们可以从中推断出因为成员test.i是测试的子对象,所以它们可能具有相同的地址.
一旦你深入了解程序中的所有对象,你真正拥有的是标量值和相邻位域的大集合.这些被称为标准中的存储位置.这些是真正占据空间的东西.其余的对象都是以某种方式组成的.
A memory location is either an object of scalar type or a maximal sequence of adjacent bit-fields all having non-zero width. [ Note: VarIoUs features of the language,such as references and virtual functions,might involve additional memory locations that are not accessible to programs but are managed by the implementation. — end note ]