直接上代码:
#include "stdafx.h"
#include
class Base
{
// 没有虚析构函数
};
class Derived : public Base
{
public:
Derived() = default;
Derived(int int_) : i_(int_) {}
~Derived() {
int i = 0;
}
int i_{ 0 };
};
int main()
{
{
Derived* sub_ptr = new Derived(123); // shared_ptr 可以调用到Derived的析构函数
//Base* sub_ptr = new Derived(123); // shared_ptr 将调用不到Derived的析构函数, 造成内存泄漏!!!
std::shared_ptr
}
return 0;
}
Derived* sub_ptr = new Derived(123); // shared_ptr 可以调用到Derived的析构函数 的实现:
1 通过模板构造函数,编译器已知指针的具体子类型,
template
explicit shared_ptr(_Ux *_Px) // 此处_Ux即是Derived, _Px是Derived*类型
{ // construct shared_ptr object that owns _Px
_Resetp(_Px);
}
2
template
void _Resetp(_Ux *_Px)
{ // release, take ownership of _Px
_TRY_BEGIN // allocate control block and reset
_Resetp0(_Px, new _Ref_count<_Ux>(_Px)); // 生成_Ref_count_base的子类_Ref_count<_Ux>,并保存具体指针类型
_CATCH_ALL // allocation failed, delete resource
delete _Px;
_RERAISE;
_CATCH_END
}
3 通过_Ref_count::_Destroy析构所管理的具体对象
template
class _Ref_count
: public _Ref_count_base
{ // handle reference counting for object without deleter
public:
_Ref_count(_Ty *_Px)
: _Ref_count_base(), _Ptr(_Px)
{ // construct
}
private:
virtual void _Destroy() _NOEXCEPT
{ // destroy managed resource
delete _Ptr; // !!! 析构 构造时传进来的具体类型!!!
}
virtual void _Delete_this() _NOEXCEPT
{ // destroy self
delete this;
}
_Ty * _Ptr;
};
附相关类简介:
shared_ptr和weak_ptr的基类
template
class _Ptr_base
{ // base class for shared_ptr and weak_ptr
。。。
private:
_Ty *_Ptr;
_Ref_count_base *_Rep;
。。。
};
template
class shared_ptr : public _Ptr_base<_Ty> {。。。}
template
class weak_ptr : public _Ptr_base<_Ty> {。。。}
引用计数基类
class _Ref_count_base
{ // common code for reference counting
private:
virtual void _Destroy() _NOEXCEPT = 0;
virtual void _Delete_this() _NOEXCEPT = 0;
private:
_Atomic_counter_t _Uses; // 强引用计数,对应shared_ptr 对象数目
_Atomic_counter_t _Weaks; // 弱引用计数,对应weak_ptr 对象数目
...
}
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
默认deleter
template
class _Ref_count
: public _Ref_count_base
{ // handle reference counting for object without deleter
public:
_Ref_count(_Ty *_Px)
: _Ref_count_base(), _Ptr(_Px)
{ // construct
}
private:
virtual void _Destroy() _NOEXCEPT
{ // destroy managed resource
delete _Ptr; // !!! 析构 构造时传进来的具体类型!!!
}
virtual void _Delete_this() _NOEXCEPT
{ // destroy self
delete this;
}
_Ty * _Ptr;
};
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
自定义deleter