reinterpret_cast from object to first member

浪尽此生 提交于 2019-11-30 22:20:52

Yes, because both classes here are standard-layout types, you can convert between &b and &b.a.

reinterpret_cast<A*>(p) is defined to be the same as static_cast<A*>(static_cast<void*>(p)), (5.2.10p7) so both your questions are equivalent.

For standard-layout classes, the address of the struct/class is the same as the address of its first non-static member (9.2p19). And static_cast to/from void* will preserve the address (5.2.9p13), meaning the result will be valid.

If the classes were not standard-layout, you could not rely on this behavior.

Formal answer: Yes, there are situations when you can do that (see the answer of @interjay).

Practical answer: Please don't do that. Really. Mainly when the straight path is available:

b.a.foo();

In other words, don't use typecasts if there is at least a minimal chance to avoid them.

bruziuz

If you're interesting in C++98,2003:

Q1 and Q2 are identical constructions.

Your types are PODs. It is exist guarantee that POD has no padding at the beginning during instancing....But it is not exist garantees during inheritance. So reinterpret_cast is unsafe... my question about POD layout

"In real life" it is rather safe, because most of compilers perform memory layout during inheritance like http://phpcompiler.org/articles/virtualinheritance.html

But be aware of the risk that A object base address and B object base address can have potentionally different values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!