C++智能指针类型转换

  • 2019 年 11 月 7 日
  • 筆記

#include <iostream>  #include <memory>    struct Base  {      int a;      virtual void f() const { std::cout << "I am base!n";}      virtual ~Base(){}  };    struct Derived : Base  {      void d()      { std::cout << "Derived:d()n"; }      void f() const override      { std::cout << "I am derived!n"; }      ~Derived(){}  };    int main(){      auto basePtr = std::make_shared<Base>();      std::cout << "Base pointer says: ";      basePtr->f();        auto derivedPtr = std::make_shared<Derived>();      std::cout << "Derived pointer says: ";      derivedPtr->f();          // 上行的转换(派生类到基类的转换)      std::cout << "Derived pointer static_pointer_cast to Base says: ";      std::static_pointer_cast<Base>(derivedPtr)->f();          // 直接转型,不构造临时 shared_ptr      // 下行的转换(基类到派生类的转换)      std::cout << "Base pointer static_cast to derived says: ";      static_cast<Derived*>(basePtr.get())->d();        // 构造临时 shared_ptr ,然后调用 operator->      // 下行的转换(基类到派生类的转换)      std::cout << "Base pointer static_pointer_cast to derived says: ";      std::static_pointer_cast<Derived>(basePtr)->d();        // 转换成对象      // 下行的转换(基类到派生类的转换)      Derived& derived = static_cast<Derived&>(*basePtr);      std::cout << "Base pointer static_cast to derived Obeject says: ";      derived.d();        // std::cout << "Base pointer dynamic_cast to derived says: ";      // dynamic_cast<Derived*>(basePtr.get())->f();  //段错误        // Derived& derived1 = dynamic_cast<Derived&>(*basePtr);      // derived1.d();       // 异常        // 下行的转换(基类到派生类的转换)      auto downcastedPtr = std::dynamic_pointer_cast<Derived>(basePtr);      if(downcastedPtr)      {          std::cout << "Base pointer dynamic_pointer_cast to derived says: ";          downcastedPtr->d();      }        // All pointers to derived share ownership      std::cout << "Pointers to underlying derived: "              << derivedPtr.use_count()              << "n";  }