dynamic_cast from “void *”

后端 未结 6 814
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 12:17

According to this, void* has no RTTI information, therefore casting from void* is not legal and it make sense.

If I remember correctly,

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 12:51

    To add to Tony's nice answer, this little code snippet helps me for some reason. First, we establish a simple hierarchy. Then, we see if dynamic_cast can "survive" a static_cast. Before this experiment I thought "the run time type information is there, dynamic cast should figure it out." Now I realize "dynamic_cast must have to look up its information based on some tables the compiler is aware of, so it can't have some magical power."

    #include 
    #include 
    
    using namespace std;
    
    class A {
      protected:
      virtual void foo() { cout << "A" << endl; }
    };
    
    class B1 : public A {
      private:
      virtual void foo() override { cout << "B1" << endl; }
    };
    
    class B2 : public A {
      public:
      virtual void foo() override { cout << "B2" << endl; }
    };
    
    int main(int argc, char **argv) {
      B1 b1;
      // undefined behavior even though dynamic_cast didn't return null
      dynamic_cast(
          static_cast(
            static_cast(&b1)))->foo();
      // dynamic_cast returns null here though
      assert (!dynamic_cast
              (static_cast
               (static_cast
                (static_cast(&b1)))));
    }
    

提交回复
热议问题