dynamic_pointer_cast不是语言关键字,在标准库<memory>中定义,位于std命名空间中,专用于智能指针shared_ptr的转换。可以理解为智能指针领域的dynamic_cast操作符。 总结一下:它们的基本区别,就是dynamci_cast用于裸指针和引用等动态类型的转型,而dynamic_pointer_cast主要用于智能指针的转型。 例子: //注意:dynamic_po...
//2.智能指针转换 std::shared_ptr<Father> father(new Son(son)); 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 此时son就是向上转换。无需显式转换既可以编译通过。 2、dynamic_cast 一般用于有继承关系的类之间的向下转换。 3、dynamic_pointer_cast 当指针是智能指针时候,向下转换,...
总结下来就是:只要抽象的程度足够,就不需要dynamic_cast。如果抽象程度不够,当然是设计的缺陷。3、但...
不同之处在于,shared_dynamic_cast只适用于shared_ptr<>的,而dynamic_pointer_cast适用于任何类型的...
第一,在容器中存储指向派生类的指针,尽量避免以下dynamic_cast的用法 classWindow { ... };classSpecialWindow:publicWindow {public:voidblink(); ... }; typedef//see Item 13 for infostd::vector<std::tr1::shared_ptr<Window> > VPW;//on tr1::shared_ptrVPW winPtrs; ...
std::shared_ptr<T> static_pointer_cast( std::shared_ptr<U>&& r ) noexcept; (2) (since C++20) template< class T, class U > std::shared_ptr<T> dynamic_pointer_cast( const std::shared_ptr<U>& r ) noexcept; (3) (since C++11) ...
shared_ptr<CBase>spBaseDown; spBaseDown= make_shared<CBase>(); spDeriveDown= dynamic_pointer_cast<CDerive>(spBaseDown);if(spDeriveDown == NULL)//由于会进行类型的检查,这边是返回NULLcout <<"spDeriveDown is null"<<endl;/*shared_ptr<CDerive> spDeriveDown; ...
那就不懂了, dynamic cast到底有什么用... 按照1L的回复我写了如下代码 : //p.h class P{ }; //s.h #include "p.h" class S : public P{ }; //main.cpp #include <iostream> #include "s.h" int main(){ //std::shared_ptr<P> x(new S); //std::shared_ptr<S> y = std::...
当指针是智能指针时候,向下转换,用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>(...
template <class Ty, class Other> shared_ptr<Ty> dynamic_pointer_cast(const shared_ptr<Other>& sp); ParametersTy The type controlled by the returned shared pointer. Other The type controlled by the argument shared pointer. sp The argument shared pointer.Remarks...