[英]C struct Inheritance vs C++ POD struct Inheritance
Suppose I use the fairly common idiom to define struct inheritance in my_header.h
: 假设我使用相当普遍的惯用法在
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. 现在,在我的C代码中,我可以执行
binstance._as_A.a_field
,或者可以将指向B的指针转换为指向A的指针,依此类推。
My question is this. 我的问题是这个。 Suppose that I now define a new C++ header
my_header.hpp
: 假设我现在定义了一个新的C ++头文件
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 . 假设我这样做是为了确保B是POD类型 。
Am I guaranteed that the memory layout of a B instance is the same in C and C++? 我是否可以保证B实例的内存布局在C和C ++中相同?
Suppose I do this taking care to make sure B is a POD type.
假设我这样做是为了确保B是POD类型。
As pointed out in the comments, B
will never be a POD type, because it will never be a standard-layout class. 正如评论中指出的那样,
B
永远不会是POD类型,因为它永远不会是标准布局类。
7 A standard-layout class is a class that:
7 标准布局类是这样的类:
[...]
[...]
(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
(7.5)-在派生程度最高的类中没有非静态数据成员,并且在最多一个具有非静态数据成员的基类中,或者没有具有非静态数据成员的基类,并且
[...]
[...]
10 A POD struct 110 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).
10 POD结构 110是既是琐碎类又是标准布局类的非联盟类,并且不具有非POD结构,非POD联合(或此类数组)类型的非静态数据成员。 。 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).
类似地, POD联合是既是普通类又是标准布局类的联合,并且不具有非POD结构,非POD联合(或此类数组)类型的非静态数据成员。 A POD class is a class that is either a POD struct or a POD union.
POD类是可以是POD结构或POD联合的类。
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.
这很重要,因为具体的实现通常确实会按照您希望的方式(作为ABI的一部分)定义布局顺序,但这还不足以满足您的需求。
No. The C++ standard draft N4296 states: 否。C++标准草案N4296指出:
10 Derived classes
10个派生类
5 The order in which the base class subobjects are allocated in the most derived object (1.8) is unspecified.5未指定在最派生对象(1.8)中分配基类子对象的顺序。 [...]
[...]
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.8 [注:基类子对象的布局(3.7)与相同类型的大多数派生对象的布局不同。 [...] ]
[...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.