C++ 智能指针的使用

// 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;
}

 

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值