码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-03-31 19:02:34      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:智能指针、c++

//智能指针可以自动销毁,用引用计数技术实现
#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;
                                }
                }
};


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

标签:智能指针、c++

原文地址:http://green906.blog.51cto.com/10697569/1758892

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!