#include <iostream>
#include <memory>
class A{
public:
virtual ~A() =default;//must have a virtual otherwise complie err: not polymorphic
};
class B: public
A{
};
typedef std::shared_ptr<A> APtr;
typedef std::shared_ptr<B> BPtr;
void test_pt(APtr p){
if (BPtr b =std::dynamic_pointer_cast<B>(p))
{
std::cout<<"bbb " << b <<std::endl;
}
else{
std::cout<<"nnn" <<std::endl;
}
}
int main(int argc,constchar * argv[])
{
void test1();
APtr a(newA());
BPtr b(newB());
APtr c(newB());
std::cout<<std::dynamic_pointer_cast<A>(b)
<<std::endl;//upcast, not 0
std::cout<<std::dynamic_pointer_cast<B>(a)
<<std::endl;//downcast, 0
std::cout<<std::dynamic_pointer_cast<B>(c)
<<std::endl;//downcast, not 0
test_pt(b);
std::cout<<"xxx " << b <<std::endl;//not
0
std::cout <<"Hello, World!\n";
return0;
}
0x100100a50
0x0
0x100100a80
bbb 0x100100a50
xxx 0x100100a50
Hello, World!
---------refernce------------------
http://msdn.microsoft.com/en-us/library/bb982967.aspx
http://stackoverflow.com/questions/14877626/up-casting-stdshared-ptr-using-stddynamic-pointer-cast