智能指针相关

  1. 实现一个智能指 https://github.com/chenshuo/recipes/blob/master/string/StringTrivial.h
//智能指针shared_ptr代码实现
template<typename T>
class SharePtr
{
public:
	SharePtr(): m_ptr(nullptr), m_count(new size_t(0))	{}
	SharePtr(T* t = nullptr): m_ptr(t), m_count(new size_t)
	{
		if (m_ptr == nullptr)	m_count = 0;
		else	m_count = 1;
	}
	
	//拷贝构造函数
	SharePtr(const SharePtr& p): m_ptr(p.m_ptr), m_count(p.m_count)
	{
		if (m_ptr != nullptr)	++(*m_count);
	}
	
	//拷贝赋值运算
	SharePtr& operator=(const SharePtr& p)
	{
		if (m_ptr != p.m_ptr)
		{
			if (m_ptr != nullptr && --(*m_count) == 0)
			{
				delete m_ptr;
				delete m_count;
				m_ptr = nullptr;
				m_count = nullptr;
			}
			m_ptr = p.m_ptr;
			m_count = p.m_count;
			if (m_ptr != nullptr)	++(*m_count);
		}
		return *this;
	}

	T& operator*()
	{
		return *m_ptr;
	}
	T* operator->()
	{
		return m_ptr;
	}
	
	~SharePtr()
	{
		if (m_ptr != nullptr && --(*m_count) == 0)
		{
			delete m_ptr;
			delete m_count;
			m_ptr = nullptr;
			m_count = nullptr;
		}
	}
private:
	T* m_ptr;
	size_t* m_count;
};


#include<iostream>
template <typename T>
class SmartPtr;

template <typename T>
class U_ptr
{
    private:
        friend class SmartPtr<T>;

        U_ptr(T* ptr) : p(ptr), count(1) {}
        ~U_ptr() {delete p;}

        T* p;
        int count;
};

template <typename T>
class SmartPtr
{
    public:
        SmartPtr(T* ptr) : rp(new U_ptr<T>(ptr)) {}
        SmartPtr(const SmartPtr<T>& sp) : rp(sp.rp) {++rp->count;}
        SmartPtr& operator=(const SmartPtr<T>& rhs)
        {
            ++rhs.rp->count;
            if(--rp->count == 0)
                delete rp;
            rp = rhs.rp;
            return *this;
        }
        T& operator*()
        {
            return *(rp->p);
        }
        T* operator->()
        {
            return rp->p;
        }
        ~SmartPtr()
        {
            if (--rp->count == 0)
                delete rp;
        }
    private:
        U_ptr<T>* rp;
};
  1. 环形引用问题举例
//环行引用
class Node
{
public:
	Node()
	{
		cout << "Node()" << endl;
	}
	~Node()
	{
		cout << "~Node()" << endl;
	}
private:
	shared_ptr<Node> m_pre;
	shared_ptr<Node> m_next;
};

int main()
{
	share_ptr<Node> p1(new Node());
	share_ptr<Node> p2(new Node());
	
	p1->m_next = p2;
	p2->m_pre = p1;
}
全部评论

相关推荐

点赞 评论 收藏
分享
11-30 11:07
河南大学 Java
宇宙厂 测开 n*15
丘丘给个offer:有后选后
点赞 评论 收藏
分享
评论
1
1
分享
牛客网
牛客企业服务