c++ - 这种贬低是否会导致未定义的行为?

标签 c++ undefined-reference downcast static-cast

鉴于此示例:

  class Base
  {
      public:
      void foo() {}; 
  };

  class Derived : public Base
  {     
  };

  int main()
  {
      Base b;
      Derived* d = static_cast<Derived*>(&b);
      d->foo();
  }

我只有三种情况:当 void foo():

  • Base的成员,
  • 并且当它是 Derived 的成员时,
  • 以及当它是BaseDerived 的成员时。

我的问题是:

  • 成员访问表达式 d->foo() 在这三种情况下都是未定义的行为吗?

  • 如果成员访问表达式是 UB,唯一的解决方法是使用 dynamic_cast 吗?

最佳答案

来自the C++ standard §7.6.1.9.11

A prvalue of type “pointer to cv1 B”, where B is a class type, can be converted to a prvalue of type “pointer to cv2 D”, where D is a complete class derived from B,

...

If the prvalue of type “pointer to cv1 B” points to a B that is actually a base class subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the behavior is undefined.

所以使用static_cast仅当您知道(通过其他方式)强制转换有效时,向下转换才有效。如果您采取 Base不是 Derived并使用 static_cast为了假装是这样,即使在尝试取消引用指针之前,您也已经调用了未定义的行为。所以你可以删除 d->foo() line 和仍然有未定义的行为。是 Actor 阵容不好。

如果您的目标是有条件地检查是否有子类的实例,那么您需要 dynamic_cast .

关于c++ - 这种贬低是否会导致未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71505316/

相关文章:

c++ - 在 C++ 中,是否可以将 CRTP 与私有(private)基一起使用?

c++ - 对派生对象的 C++ 虚函数调用是否通过 vtable?

C 错误 : undefined reference to function, 但已定义

gcc - C程序找不到包含在头文件中的函数

c++ - undefined reference

swift - 基本 : Connecting multiple (View-)Controllers the right way

c++ - C++中的直接构造函数调用

c++ - POCO 记录器包装器

c++ - 方法中使用的静态模板成员数组sizeof

c# - 为什么我们需要在 C# 中进行向上转型和向下转型?