std::dynamic_pointer_cast的别名是dynamic_pointer_cast,它是该函数的常用简称。 该函数的作用是将一个指向基类的shared_ptr或weak_ptr对象转换为指向派生类的shared_ptr对象。它会检查指针的动态类型,如果类型匹配,则返回指向派生类的shared_ptr对象;如果类型不匹配,则返回一个空的shared_ptr对象。
`dynamic_cast` 在运行时检查类型的合法性,如果转换合法,则返回转换后的类型;如果不合法,且用于指针,则返回空指针,用于引用,则抛出 `std::bad_cast` 异常。 二者的主要区别在于它们作用的对象类型: 1. `std::dynamic_pointer_cast` 用于 `std::shared_ptr` 智能指针。 2. `dynamic_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())...
正如评论中所说,您必须创建一个新函数:
这行代码尝试将 basePtr 转换为 std::shared_ptr<Derived>。dynamic_pointer_cast 会在运行时检查转换是否安全(即 basePtr 是否确实指向一个 Derived 类对象)。如果转换成功,derivedPtr 将被赋予新的类型,并指向原来的对象;如果转换失败,derivedPtr 将为nullptr。
shared_ptr的类型转换不能使用一般的static_cast,这种方式进行的转换会导致转换后的指针无法再被shared_ptr对象正确的管理。应该使用专门用于shared_ptr类型转换的 static_pointer_cast<T>() , const_pointer_cast<T>() 和dynamic_pointer_cast<T>()。
shared_ptr的类型转换不能使用一般的static_cast,这种方式进行的转换会导致转换后的指针无法再被shared_ptr对象正确的管理。应该使用专门用于shared_ptr类型转换的 static_pointer_cast<T>() , const_pointer_cast<T>() 和dynamic_pointer_cast<T>()。
auto pointer = std::make_shared<int>(10); auto pointer2 = pointer; // 引用计数+1 auto pointer3 = pointer; // 引用计数+1 int *p = pointer.get(); // 这样不会增加引用计数 std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 3 ...
namespace tr1 { // TR1 additionsusing _STD allocate_shared;using _STD bad_weak_ptr;using _STD const_pointer_cast;using _STD dynamic_pointer_cast;using _STD enable_shared_from_this;using _STD get_deleter;using _STD make_shared;using _STD shared_ptr;using _STD static_pointer_cast;using _...
否则,新的shared_ptr将与r,但如果dynamic_cast由dynamic_pointer_cast返回空指针。 让Y成typenamestd::shared_ptr<T>::element_type,然后产生的std::shared_ptr%27s存储的指针将通过按%29的顺序调用%28获得: 1%29static_cast<Y*>(r.get())... 2%29dynamic_cast<Y*>(r.get())%28如果结果为dynamic_cas...