1. 几种构造函数
shared_ptr p(q) p管理内置指针q所指的对象;q必须指向new分配的内存,且能够转换为T类型
shared_ptr p(q,d) p接管了内置指针q所指向的对象的所有权。q必须能转换为T类型。p将使用可调用对象d来代替delete
shared_ptr p(p2,d) p是shared_ptr p2的拷贝,唯一的区别是p将使用可调用对象d来代替delete
1.1 如果参数是shared_ptr引用,那么调用底层的construct函数,计算器加1,否则如果是&&引用,就调用底层的move
template <class _Ty2>
shared_ptr(const shared_ptr<_Ty2>& _Right, element_type* _Px) noexcept {
// construct shared_ptr object that aliases _Right
this->_Alias_construct_from(_Right, _Px);
}
template <class _Ty2>
shared_ptr(shared_ptr<_Ty2>&& _Right, element_type* _Px) noexcept {
// move construct shared_ptr object that aliases _Right
this->_Alias_move_construct_from(_STD move(_Right), _Px);
}
shared_ptr(const shared_ptr& _Other) noexcept {
// construct shared_ptr object that owns same resource as _Other
this->_Copy_construct_from(_Other);
}
template <class _Ty2, enable_if_t<_SP_pointer_compatible<_Ty2, _Ty>::value, int> = 0>
shared_ptr(const shared_ptr<_Ty2>& _Other) noexcept {
// construct shared_ptr object that owns same resource as _Other
this->_Copy_construct_from(_Other);
}
shared_ptr(shared_ptr&& _Right) noexcept {
// construct shared_ptr object that takes resource from _Right
this->_Move_construct_from(_STD move(_Right));
}
template <class _Ty2, enable_if_t<_SP_pointer_compatible<_Ty2, _Ty>::value, int> = 0>
shared_ptr(shared_ptr<_Ty2>&& _Right) noexcept {
// construct shared_ptr object that takes resource from _Right
this->_Move_construct_from(_STD move(_Right));
}
1.2 底层函数:_Move_construct_from
template <class _Ty2>
void _Move_construct_from(_Ptr_base<_Ty2>&& _Right) noexcept {
// implement shared_ptr's (converting) move ctor and weak_ptr's move ctor
_Ptr = _Right._Ptr;
_Rep = _Right._Rep;
_Right._Ptr = nullptr;
_Right._Rep = nullptr;
}
template <class _Ty2>
void _Alias_move_construct_from(shared_ptr<_Ty2>&& _Other, element_type* _Px) noexcept {
// implement shared_ptr's aliasing move ctor
_Ptr = _Px;
_Rep = _Other._Rep;
_Other._Ptr = nullptr;
_Other._Rep = nullptr;
}
1.3 底层函数:construct_from
template <class _Ty2>
void _Copy_construct_from(const shared_ptr<_Ty2>& _Other) noexcept {
// implement shared_ptr's (converting) copy ctor
_Other._Incref();
_Ptr = _Other._Ptr;
_Rep = _Other._Rep;
}
template <class _Ty2>
void _Alias_construct_from(const shared_ptr<_Ty2>& _Other, element_type* _Px) noexcept {
// implement shared_ptr's aliasing ctor
_Other._Incref();
_Ptr = _Px;
_Rep = _Other._Rep;
}