gpt4 book ai didi

c++ - 来自指向派生类的指针的 `static_cast(static_cast(derived))` 何时有效?

转载 作者:行者123 更新时间:2023-11-30 02:14:33 28 4
gpt4 key购买 nike

本题不涉及多态,即不涉及虚方法,不涉及虚基类。以防万一,我的案子不涉及这些。

假设我有一个类 Derived它有一个明确的可访问父类型 Base ,没有多态性(没有虚方法,没有虚基类),但可能涉及间接和/或多重继承。进一步假设我有一个有效的指针 Derived *derived(指向 Derived 类型的对象或其子类)。

在这种情况下,我相信static_cast<Base*>(derived)已验证(导致有效的可用指针)。当 Base 之间的祖先链和 Derived涉及多重继承,这个static_cast可能意味着指针调整以定位 Base Derived 中的实例实例。为此,编译器需要知道继承链,他在本例中就是这样做的。但是,如果中间转换为 void *被插入,继承链信息对编译器是隐藏的。对于哪个继承链,这样的静态转换仍然有效?我希望出现以下情况之一:

  • 完全没有?访问 static_cast来自 void 指针是未定义的行为,除非指针确实指向确切的类型。
  • 对于没有多重继承的所有链?然后,编译器可以保证 Base始终位于 Derived 的开头- 但标准是怎么说的?
  • 对于 Base 所在的所有链式店在所有中间多重继承链的第一个父类中找到?也许是Base的开始和 Derived仍然匹配吗?
  • 总是? static_cast to void 指针总是可以调整到第一个父级的开始,并且 static_cast从 void 指针撤消该调整。但是对于多重继承,“第一个 parent ”不一定是所有 parent 的 parent 。

最佳答案

static_cast<Base*>(static_cast<void*>(derived))在 C++ 标准中有一个名称。它叫做 reinterpret_cast .它在 [expr.reinterpret.cast] paragraph 7 中指定:

An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of object pointer type is converted to the object pointer type “pointer to cv T”, the result is static_­cast<cv T*>(static_­cast<cv void*>(v)). [ Note: Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value. — end note ]

A reinterpret_cast我们是在告诉编译器将指针视为其他东西。编译器无法或将根据此指令进行任何调整。如果我们撒谎,那么行为就是未定义的。标准是否表示​​这样的 reinterpret_cast已验证?它确实如此。在 [basic.compound] paragraph 4 中定义了指针互换性的概念。 :

Two objects a and b are pointer-interconvertible if:

  • they are the same object, or
  • one is a union object and the other is a non-static data member of that object ([class.union]), or
  • one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, any base class subobject of that object ([class.mem]), or
  • there exists an object c such that a and c are pointer-interconvertible, and c and b are pointer-interconvertible.

If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a reinterpret_­cast. [ Note: An array object and its first element are not pointer-interconvertible, even though they have the same address. — end note ]

第三个项目符号是您的答案。类层次结构中的对象必须遵守限制(从顶层到最派生的 standard layout),只有这样才能保证转换给出定义明确的结果。

关于c++ - 来自指向派生类的指针的 `static_cast<Base*>(static_cast<void*>(derived))` 何时有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57636959/

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