首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

boost中的shared_ptr是如何实现删除析构函数为私有的指针的

2013-04-02 
boost中的shared_ptr是怎么实现删除析构函数为私有的指针的?头文件不加了,主要代码如下class TA{protected

boost中的shared_ptr是怎么实现删除析构函数为私有的指针的?
头文件不加了,主要代码如下


class TA
{
protected:
virtual ~TA() {}
};
class TB : public TA
{
public:
virtual ~TB() { cout << "~TB()" << endl; }
};



void main()
{
shared_ptr<TA> tA(new TB);  //没问题

 TA *pp = new TB;
 delete pp;                  //error C2248: “TA::~TA”: 无法访问 protected 成员(在“TA”类中声明)
}

请问boost中的shared_ptr是怎么实现删除析构函数为私有的指针的?
boost?shared_pt
[解决办法]
它内部记载的类型是 TB,不是 TA,你获取指针的时候,它才临时转换成 TA 给你。
[解决办法]

 TA *pp = new TB;
    shared_ptr<TA> tA( pp );

改成这样就编译不过去了,也就是说内部记录的是TB*而不是TA*。
[解决办法]
发现VC2010中有小缺陷。

//构造函数
template<class _Ux>
explicit shared_ptr(_Ux *_Px)
{// construct shared_ptr object that owns _Px
_Resetp(_Px);
}
//对应的Resetp
template<class _Ux>
void _Resetp(_Ux *_Px)
{// release, take ownership of _Px
_TRY_BEGIN// allocate control block and reset
_Resetp0(_Px, new _Ref_count<_Ux>(_Px));
_CATCH_ALL// allocation failed, delete resource
delete _Px; //有问题的这行
_RERAISE;
_CATCH_END
}
TB* tb = new TB();
TA* ta = tb;
shared_ptr<TA> p(tb); //OK,因为delete tb;是OK的
//shared_ptr<TA> p2(ta);//NG, 因为delete ta;是NG的

热点排行