先show一个实例:
class father
{
public:
father(){}
~father(){}
virtual void fun(){cout<<"father"<<endl;}
};
class mother{
public:
mother(){}
~mother(){}
virtual void Test(int a){cout<<a<<endl;}
};
class Son:publicfather ,public mother
{
public:
Son(){}
~Son(){}
void fun(){cout<<"Son"<<endl;}
};
int _tmain(int argc,_TCHAR* argv[])
{
shared_ptr<father>f=shared_ptr<Son>();
shared_ptr<mother>m=dynamic_pointer_cast<mother>(f);
m->Test(10);
}
这个程序编译没有问题,运行时崩溃。但是将mother的Test函数前的virtual去掉时,运行结果才是正常的。从C++虚函数的角度,是不应该运行时崩溃的。不用智能指针,直接使用裸指针,运行时结果正常。如下:
int _tmain(int argc,_TCHAR* argv[])
{
father* f=new Son();
mother* m=dynamic_cast<mother*>(f);
m->Test(10);
}
这从侧面说明了智能指针的这个bug.