保证C++中基类的地址?

ano*_*non 8 c++ inheritance base-class object-address

在C struct中,我保证:

struct Foo { ... };
struct Bar {
  Foo foo;
  ...
}
Bar bar;
assert(&bar == &(bar.foo));
Run Code Online (Sandbox Code Playgroud)

现在,在C++中,如果我有:

class Foo { ... };
class Bar: public Foo, public Other crap ... {
  ...
}

Bar bar;
assert(&bar == (Foo*) (&bar)); // is this guaranteed?
Run Code Online (Sandbox Code Playgroud)

如果是这样,你能给我一个参考(如"The C++ Programming Language,page xyz")吗?

谢谢!

Jam*_*lis 10

没有保证.从C++ 03标准(10/3,class.derived):

未指定在最派生对象(1.8)中分配基类子对象的顺序.


小智 6

即使基本类的布局不能保证你想象的方式(即使成员有更多的保证),这也是有保证的:

Bar bar;
assert(&bar == (Foo*) (&bar));
Run Code Online (Sandbox Code Playgroud)

因为强制转换使用static_cast(每5.4)将&bar正确转换,并且指针到base和指向派生的指针之间的比较将类似地转换.

但是,这不能得到保证:

Bar bar;
void* p1 = &bar;
void* p2 = (Foo*)&bar;
assert(p1 == p2); // not guaranteed
Run Code Online (Sandbox Code Playgroud)