实现一个简洁版的智能指针

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现一个简洁版的智能指针相关的知识,希望对你有一定的参考价值。

//智能指针可以自动销毁,用引用计数技术实现
#include<iostream>
using namespace std;

template<class T>
class SmartPtr
{
protected:
                 T* _ptr;
                 size_t* _cout;

                 void clear()
                {
                                 if(-- *_cout == 0)
                                {
                                                 delete _ptr;
                                                 delete _cout;
                                }
                }

public:
                SmartPtr( T* ptr = 0)
                                :_ptr( ptr)
                                ,_cout( new size_t (1))
                {}

                SmartPtr( const SmartPtr& p)
                                :_ptr( p._ptr)
                                ,_cout( p._cout)
                {
                                ++ *_cout;
                }

                 SmartPtr& operator=(const SmartPtr& p)
                {
                                ++ * p._cout;
                                clear();
                                _ptr = p._ptr;
                                _cout = p._cout;
                                
                                 return *this ;
                }

                ~SmartPtr()
                {
                                clear();
                }

                 T* operator->()
                {
                                 if(_ptr)
                                {
                                                 return _ptr;
                                }
                }

                 T& operator*()
                {
                                 if(_ptr)
                                {
                                                 return *_ptr;
                                }
                }
                const T* operator->()const
                {
                                 if(_ptr)
                                {
                                                 return _ptr;
                                }
                }

                 const T& operator*()const
                {
                                 if(_ptr)
                                {
                                                 return *_ptr;
                                }
                }
};


以上是关于实现一个简洁版的智能指针的主要内容,如果未能解决你的问题,请参考以下文章

shared_ptr智能指针模板类的简单实现(c++11)

智能指针的原理和简单实现

智能指针的概念和实现

智能指针 与 oc中的指针

C++单线程智能指针实现

有哪些 C++ 智能指针实现可用?