c++ 智能指针的向下转换 向下塑型 cast
class A { public: void test() { std::cout << "test" << std::endl; } }; class B : public A { public: void test2() { std::cout << "test2" << std::endl; } }; std::unique_ptr<A> Get() { std::unique_ptr<A> b(new B); return b; } int main() { auto o = Get(); // 如何转换为 std::unique_ptr<B> ? system("pause"); return 0; }
需取出原始指针:
B* ptr = dynamic_cast<B*>(o.get());
int main() { auto o = Get(); std::cout << typeid(o).name() << std::endl; auto x = reinterpret_cast<B*>(o.release()); std::unique_ptr<B> b(x); std::cout << typeid(b).name() << std::endl; system("pause"); return 0; }