c++ primer 13.5.1 智能指针

class HasPtr
{
public:
	HasPtr(int nVal, int *ptr = NULL):m_nVal(nVal)
		                      ,m_ptr(ptr)
	{

	}

	inline int  GetValue() const { return m_nVal; }
	inline void SetValue(int &nVal){m_nVal = nVal;}

	inline int* GetPtr() const {return m_ptr;}
	inline void SetPtr(int *ptr){m_ptr = ptr;}

	inline int  GetPtrValue() const {return *m_ptr;}
	inline void SetPtrValue(int nVal) {*m_ptr = nVal;}

private:
	int          m_nVal;
	int         *m_ptr;
};

class HasPtrOther;

class U_Ptr
{
	friend class HasPtrOther;

	U_Ptr(int *p) : m_nUsed(1), m_pn(p)
	{

	}

	~U_Ptr()
	{
		if(m_pn)
		{
			delete m_pn;
			m_pn = NULL;
		}
	}

	int     m_nUsed;     // 使用计数
	int     *m_pn;
};

class HasPtrOther
{
public:
	HasPtrOther(int nVal, int *ptr) : m_nVal(nVal)
		                            , m_pU(new U_Ptr(ptr))
	{

	}

	HasPtrOther(const HasPtrOther &rhs): m_nVal(rhs.m_nVal)
									   , m_pU(rhs.m_pU)
	{
		++m_pU->m_nUsed;
	}

	~HasPtrOther()
	{
		if(0 == --m_pU->m_nUsed)
		{
			delete m_pU;
			m_pU = NULL;
		}
	}


	HasPtrOther & HasPtrOther::operator=(const HasPtrOther &rhs)
	{
		++rhs.m_pU->m_nUsed;

		if(0 == --m_pU->m_nUsed)
		{
			delete m_pU;
			m_pU= NULL;
		}

		m_nVal = rhs.m_nVal;
		m_pU   = rhs.m_pU;

		return *this;
	}

	inline int* GetPtr() const {return m_pU->m_pn;}
	inline void SetPtr(int *ptr){m_pU->m_pn = ptr;}

	inline int  GetPtrValue() const {return *m_pU->m_pn;}
	inline void SetPtrValue(int nVal) {*m_pU->m_pn = nVal;}


private:
	int    m_nVal;
	U_Ptr  *m_pU;
};



inline void TestPtr()
{
	int *ptr = new int;

	HasPtr p1(88, ptr);
	
	HasPtr p2 = p1;

	p1.SetPtrValue(20);
	std::cout << p2.GetPtrValue();

	RELEASE_MEMORY(ptr);

	ptr = new int();

	HasPtrOther ptr1(77, ptr);
	HasPtrOther ptr2 = ptr1;

	
	//HasPtrOther ptr3(66, new int(55));

	//ptr3 = ptr2;

	vector<HasPtrOther> vtr;
	vtr.push_back(ptr1);


}

你可能感兴趣的:(c++ primer 13.5.1 智能指针)