1、std::static_pointer_cast():当指针是智能指针时候,向上转换,用static_cast 则转换不了,此时需要使用static_pointer_cast。 2、std::dynamic_pointer_cast():当指针是智能指针时候,向下转换,用dynamic_cast 则转换不了,此时需要使用dynamic_pointer_cast(此处注意:base基类需要至少有一个virtual成员函数(即多态类...
一、static_cast和dynamic_cast区别: 1、static_cast:向上转换,例如:基类向派生类转换 2、dynamic_cast:向下转换,例如:派生类向基类转换 二、static_poonter_cast和dynamic_pointer_cast区别同上,不过这两个只适用于智能指针
否则,新的 shared_ptr 将与r 的初始值共享所有权,但若 dynamic_pointer_cast 所进行的 dynamic_cast 返回空指针,则它为空。 令Y 为typename std::shared_ptr<T>::element_type,则将分别通过求值下列表达式,获得所得 std::shared_ptr 的存储指针: 1,2) static_cast<Y*>(r.get())...
dynamic_cast可用于继承体系中的向下转型,即将基类指针转换为派生类指针,比static_cast更严格更安全。dynamic_cast在执行效率上比static_cast要差一些,但static_cast在更宽上范围内可以完成映射,这种不加限制的映射伴随着不安全性。static_cast覆盖的变换类型除类层次的静态导航以外,还包括无映射变换、窄化变换(这种变换...
当指针是智能指针时候,向下转换,用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>(...
(1)static_cast 用法:static_cast < type-id > ( exdivssion ) 该运算符把exdivssion转换为type-id类型,但没有运行时类型检查来保证转换的安全性。它主要有如下几种用法: ①用于类层次结构中基类和子类之间指针或引用的转换。 a. 进行上行转换(把子类的指针或引用转换成基类表示)是安全的; ...
We use dynamic_cast and dynamic_pointer_cast to do a bunch of downcasts (base -> derived casts). I found that all dynamic_pointer_casts are unused: they are either upcasts, or casting to itself. So I changed them to static_pointer_cast for upcasts, and no-op to no-casts. We do...
2。static_cast:编译时检查,用于非多态的转换,可以转换指针及其他,比如:int->float还可以逆隐式转换,比如:比如:int->char。It is left to the programmer to ensure that the results of astatic_castconversion are safe. 3。对于指针的转换:Thedynamic_castandstatic_castoperators move a pointer throughout ...
在简单的情况下,上面这种类型转换可以很好地工作,但在C++中往往还是不够的,为此ANSI-C++新标准定义的四个转换符,即static_cast、dynamic_cast、reinterpret_cast和const_cast。同时在C++环境中,原先的C-Style的类型转换仍旧可以使用。 1) static_cast 用法:static_cast <typeid> (expression) ...
1) static_cast 用法:static_cast <typeid> (expression) 说明:该运算符把expression转换为typeid类型,但没有运行时类型检查来确保转换的安全性。 用途: a)用于类层次结构中基类和派生类之间指针或者引用的转换。up-casting (把派生类的指针或引用转换成基类的指针或者...