1、std::static_pointer_cast():当指针是智能指针时候,向上转换,用static_cast 则转换不了,此时需要使用static_pointer_cast。 2、std::dynamic_pointer_cast():当指针是智能指针时候,向下转换,用dynamic_cast 则转换不了,此时需要使用dynamic_pointer_cast(此处注意:base基类需
<< std::endl; } else if (std::shared_ptr<Cat> cat = std::dynamic_pointer_cast<Cat>(animal)) { std::cout << "It's a cat!" << std::endl; } else { std::cout << "Unknown animal type" << std::endl; } } int main() { std::shared_ptr<Animal> dog = std::make_shared...
1、std::static_pointer_cast():当指针是智能指针时候,向上转换,用static_cast 则转换不了,此时需要使用static_pointer_cast。2、std::dynamic_pointer_cast():当指针是智能指针时候,向下转换,用dynamic_cast 则转换不了,此时需要使用dynamic_pointer_cast。 class LidarFrame : public SensorReading; class LivoxRea...
一、static_cast和dynamic_cast区别: 1、static_cast:向上转换,例如:基类向派生类转换 2、dynamic_cast:向下转换,例如:派生类向基类转换 二、static_poonter_cast和dynamic_pointer_cast区别同上,不过这两个只适用于智能指针
1-2) 行为未定义,除非 static_cast<T*>((U*)nullptr) 为良式。 3-4) 行为未定义,除非 dynamic_cast<T*>((U*)nullptr) 为良式。 5-6) 行为未定义,除非 const_cast<T*>((U*)nullptr) 为良式。 7-8) 行为未定义,除非 reinterpret_cast<T*>((U*)nullptr) 为良式。
1. 解释std::static_pointer_cast的基本概念 std::static_pointer_cast 是C++11 引入的一个模板函数,用于智能指针(如 std::shared_ptr 或std::weak_ptr)之间的类型转换。这种转换是编译时的强制转换,不会在运行时进行检查,类似于 static_cast,但专门用于智能指针,确保转换后的指针仍然保留智能指针的内存管理功能...
1,2)static_cast<Y*>(r.get()) 3,4)dynamic_cast<Y*>(r.get()). If the result of thedynamic_castis a null pointer value, the returnedshared_ptrwill be empty. 5,6)const_cast<Y*>(r.get()) 7,8)reinterpret_cast<Y*>(r.get()) ...
r - the pointer to convert NotesThe expressions std::shared_ptr<T>(static_cast<T*>(r.get())), std::shared_ptr<T>(dynamic_cast<T*>(r.get())) and std::shared_ptr<T>(const_cast<T*>(r.get())) might seem to have the same effect, but they all will likely result in ...
static_cast <new_type> (expression) dynamic_cast <new_type> (expression) reinterpret_cast <new_type> (expression) const_cast <new_type> (expression) 可以提升转换的安全性。 static_cast <new_type> (expression) 静态转换 静态转换是最接近于C风格转换,很多时候都需要程序员自身去判断转换是否安全。比...
输出结果是:Null pointer on second type-cast 两个dynamic_cast都是下行转换,第一个转换是安全的,因为指向对象的本质是子类,转换的结果使子类指针指向子类,天经地义;第二个转换是不安全的,因为指向对象的本质是父类,“指鹿为马”或指向不存在的空间很可能发生!