1、std::static_pointer_cast():当指针是智能指针时候,向上转换,用static_cast 则转换不了,此时需要使用static_pointer_cast。 2、std::dynamic_pointer_cast():当指针是智能指针时候,向下转换,用dynamic_cast 则转换不了,此时需要使用dynamic_pointer_cast(此处注意:base基类需要至少有一个virtual成员函数(即多态类...
dynamic_pointer_cast不是语言关键字,在标准库<memory>中定义,位于std命名空间中,专用于智能指针shared_ptr的转换。可以理解为智能指针领域的dynamic_cast操作符。 总结一下:它们的基本区别,就是dynamci_cast用于裸指针和引用等动态类型的转型,而dynamic_pointer_cast主要用于智能指针的转型。 例子: //注意:dynamic_po...
当指针是智能指针时候,向下转换,用dynamic_Cast 则编译不能通过,此时需要使用dynamic_pointer_cast。 向下转换(含智能指针): struct Father { //基类Father }; struct Son:Father { //基类Father的派生类B }; std::shared_ptr<Father> father; std::shared_ptr<Son> son = std::dynamic_pointer_cast<Son>...
当指针是智能指针时候,向下转换,用dynamic_Cast 则编译不能通过,此时需要使用dynamic_pointer_cast。向下转换(含智能指针):struct Father { //基类Father }; struct Son:Father { //基类Father的派生类B }; std::shared_ptr<Father> father; std::shared_ptr<Son> son = std::dynamic_pointer_cast<Son>(...
spDeriveDown= dynamic_pointer_cast<CDerive>(spBaseDown);if(spDeriveDown == NULL)//由于会进行类型的检查,这边是返回NULLcout <<"spDeriveDown is null"<<endl; spDeriveDown->myDerive();return0; } 运行结果: 一些结论: 子类向基类转是一定没有问题的。基类转子类的话,必须基类的动态类型与要转换的...
Dynamic cast to shared_ptr. Syntax template <class Ty, class Other> shared_ptr<Ty> dynamic_pointer_cast(const shared_ptr<Other>& sp); Parameters Ty The type controlled by the returned shared pointer. Other The type controlled by the argument shared pointer. ...
dynamic_pointer_cast 是一种特殊的类型转换函数,它可以将一个对象从一个类型转换为另一个类型。它的语法类似于其他类型转换函数,例如强制类型转换。然而,dynamic_pointer_cast 有一个额外的参数,即目标类型,它指定要转换的对象的类型。 在使用 dynamic_pointer_cast 时,需要确保目标类型与原始类型兼容。如果不兼容,...
不同之处在于,shared_dynamic_cast只适用于shared_ptr<>的,而dynamic_pointer_cast适用于任何类型的...
1. `std::dynamic_pointer_cast` 用于 `std::shared_ptr` 智能指针。 2. `dynamic_cast` 用于原生指针或引用。 此外,`std::dynamic_pointer_cast` 在转换过程中还会维护 `std::shared_ptr` 的引用计数,这是它特有的特性。在使用 `std::dynamic_pointer_cast` 时,如果原始指针能成功转换为目标类型,那么转...
template <class Ty, class Other> shared_ptr<Ty> dynamic_pointer_cast(const shared_ptr<Other>& sp); 參數 Ty 控制所傳回的共用指標型別。 Other 控制共用的引數的指標型別。 sp 引數的共用的指標。 備註 樣板函式會傳回空的 shared_ptr 物件,如果dynamic_cast<Ty*>(sp.get())會傳回 null 指標。