首页 > 其他 > 详细

智能指针

时间:2014-07-19 17:05:11      阅读:309      评论:0      收藏:0      [点我收藏+]
// 智能指针
// 作用:
//        1. 管理堆内存
// 使用约束:
//        1. 不能将智能指针对象赋值给智能指针对象
//        2. 不能将栈对象取地址后赋值给智能指针
//        3. 每一个对应的堆对象地址只能赋值给一个智能指针对象

#pragma once

template<class T>
class CSmartPoint
{
    unsigned int count;
    T* p;
public:
    CSmartPoint()
    {
        count = 1;
        p = NULL;
    }

    ~CSmartPoint()
    {
        count--;

        if (p && count == 0)
        {
            delete p;
            p = NULL;
        }
    }

    CSmartPoint(T* pt)
    {
        count = 1;
        if (p)
        {
            delete p;
        }

        p = pt;
    }

    CSmartPoint(const CSmartPoint& sp)
    {
        p = sp.p;
        count = sp.count + 1;
    }

    T* get()
    {
        return p;
    }

    CSmartPoint& operator=(T* pt)
    {
        if (p == pt)
        {
            return *this;
        }

        if (p)
        {
            delete p;
        }

        p = pt;

        return *this;
    }

    T* operator->()
    {
        return p;
    }
};

智能指针,布布扣,bubuko.com

智能指针

原文:http://www.cnblogs.com/acnwcl/p/3853875.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!