C struct Inheritance vs C++ POD struct Inheritance

ⅰ亾dé卋堺 提交于 2021-01-28 12:30:41

问题


Suppose I use the fairly common idiom to define struct inheritance in my_header.h:

struct A { int a_field; ... };
struct B { struct A _as_A; int b_field; ... };

Now in my C code I can do binstance._as_A.a_field, or I can cast a pointer to B to a pointer to A, and so forth.

My question is this. Suppose that I now define a new C++ header my_header.hpp:

struct A { int a_field; ... }
struct B : A { int b_field; ... }

Suppose I do this taking care to make sure B is a POD type.

Am I guaranteed that the memory layout of a B instance is the same in C and C++?


回答1:


Suppose I do this taking care to make sure B is a POD type.

As pointed out in the comments, B will never be a POD type, because it will never be a standard-layout class.

7 A standard-layout class is a class that:

[...]

(7.5) -- either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and

[...]

10 A POD struct110 is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). Similarly, a POD union is a union that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). A POD class is a class that is either a POD struct or a POD union.

Because of that, the literal question you asked turns out irrelevant: even if the layout order were guaranteed, you still wouldn't be allowed to do what you're trying to do. This matters because concrete implementations do typically define the layout order the way you're hoping, as part of the ABI, but that's not enough for what you're after.




回答2:


No. The C++ standard draft N4296 states:

10 Derived classes
5 The order in which the base class subobjects are allocated in the most derived object (1.8) is unspecified. [...]
8 [ Note: A base class subobject might have a layout (3.7) different from the layout of a most derived object of the same type. [...] ]



来源:https://stackoverflow.com/questions/46872961/c-struct-inheritance-vs-c-pod-struct-inheritance

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