如何自己为我自己的shared_ptr实现实现别名构造函数

How to implement the aliasing constructor by own for my own shared_ptr implementation?

本文关键字:实现 shared ptr 自己的 别名 构造函数 我自己 何自己 自己      更新时间:2023-10-16

我正在尝试自己实现共享的 ptr 模板类。

shared_ptr的别名构造函数的原型是

template< class Y >
shared_ptr( const shared_ptr<Y>& r, element_type *ptr );

我已经实现了转换构造函数,如下所示,

shared_ptr<T>::shared_ptr(const shared_ptr<U> &p_ownershipObj,T* p_managedObjPtr)
      { 
         if(p_ownershipObj.m_refCountPtr) // Ql
         {
            m_managedObjectPtr=p_managedObjPtr;
            m_refCountPtr = p_ownershipObj.m_refCountPtr;
            m_refCountPtr->m_strongReferenceCount++;            
         }
      }

问题 1.如何在此处访问shared_ptr<U> m_refCountPtrm_refCountPtrshared_ptr模板类的私有成员。我知道无法访问私有成员,那么编译器可能如何实现此功能?

Boost 通过使用模板成员朋友或公开成员来解决此问题,具体取决于定义BOOST_NO_MEMBER_TEMPLATE_FRIENDS的值。

例如,好友声明如下所示:

template<class Y> friend class shared_ptr;
template<class Y> friend class weak_ptr;