gpt4 book ai didi

c++ - C 结构继承与 C++ POD 结构继承

转载 作者:太空宇宙 更新时间:2023-11-04 00:59:17 25 4
gpt4 key购买 nike

假设我使用相当常见的习惯用法在 my_header.h 中定义结构继承:

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

现在,在我的 C 代码中,我可以执行 binstance._as_A.a_field,或者我可以将指向 B 的指针转换为指向 A 的指针,等等。

我的问题是这样的。假设我现在定义一个新的 C++ 头文件 my_header.hpp:

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

假设我这样做是为了确保B 是 POD 类型

我能保证 B 实例的内存布局在 C 和 C++ 中是相同的吗?

最佳答案

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

正如评论中指出的那样,B 永远不会是 POD 类型,因为它永远不会是标准布局类。

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.

因此,您问的字面问题变得无关紧要:即使布局顺序得到保证,您仍然不能做您想做的事情。这一点很重要,因为作为 ABI 的一部分,具体实现通常会按照您希望的方式定义布局顺序,但这还不足以满足您的需求。

关于c++ - C 结构继承与 C++ POD 结构继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46872961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com