智能指针类型转换

在编写基于虚函数的多态代码时,指针的类型转换很有用,比如把一个基类指针转型为一个子类指针或者反过来。但是对于share_ptr不能使用诸如static_cast<T*>(p.get())的形式,这将导致转型后的指针无法再被shared_ptr正确管理。为了支持这样的用法,shared_ptr提供了类似的转型函数 static_pointer_cast<T>()、const_pointer_cast<T>()、dynamic_pointer_cast<T>(),它们与标准的转型操作符static_cast<T>()、const_cast<T>()和dynamic_cast<T>()类似,但返回的转型后的shared_ptr。

例如,下面的代码使用

 

   

dynamic_pointer_cast<T>()把一个shared_ptr<std::exception>向下转型为一个

shared_ptr<std::exception>,然后又用

    

static_pointer_cast<T>()重新转为

    

 

    

shared_ptr<std::exception>:

  1. shared_ptr<std::exception> sp1(new bad_exception("error"));  
  2. shared_ptr<bad_exception> sp2 = dynamic_pointer_cast<bad_exception>(sp1);  
  3. shared_ptr<std::exception> sp3 = static_pointer_cast<std::exception>(sp2);  
  4. assert(sp3 == sp1);  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值