C++ 智能指针的使用

来源:互联网 发布:sql 删除数据库语句 编辑:程序博客网 时间:2024/05/17 18:02
// auto_ptr.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"// 计数类class smart_count{public:    smart_count(int c):m_count(c){}    ~smart_count(){}    int addRef()    {        return m_count++;    }    int releaseRef()    {        if (m_count--)        {            return m_count;        }        else            return 0;    }    int getCount()    {        return m_count;    }private:    int m_count;};template <class T>class auto_ptr{public:    //! 防止隐式转换    explicit auto_ptr(T *p):ptr(p),m_csmart_count(new smart_count(1)){}    auto_ptr():ptr(NULL),m_csmart_count(NULL){}    //! 拷贝构造函数    auto_ptr(const auto_ptr<T>& t)    {        ptr = t.ptr;        m_csmart_count = t.m_csmart_count;        if (m_csmart_count)        {            m_csmart_count->addRef();        }    }    //! 重载赋值运算符    auto_ptr<T>& operator=(const auto_ptr<T>& t)    {        if (t.m_csmart_count)        {            t.m_csmart_count->addRef();        }        ptr = t.ptr;        m_csmart_count = t.m_csmart_count;        return *this;    }    //! 析构函数    ~auto_ptr()    {        if (ptr && m_csmart_count->releaseRef() <= 0)        {            delete ptr;            delete m_csmart_count;            ptr = NULL;        }    }    void prtRef()    {        printf("%d\n", m_csmart_count->getCount());    }protected:private:    smart_count *m_csmart_count;    T *ptr;    };int _tmain(int argc, _TCHAR* argv[]){    char *p = "123";    auto_ptr<char> au_p(p);    auto_ptr<char> au_p1=au_p;    au_p1.prtRef();    au_p1.~auto_ptr();    au_p.prtRef();    getchar();return 0;}

 

自己简单实现的一个智能指针类,暂时还没有重载 * 和 ->等操作符。
 

 

原创粉丝点击