智能指针的一个bug

先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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值