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

智能指针

时间:2014-07-19 17:05:40      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   art   re   

// 智能指针
// 作用:
//        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

智能指针

标签:style   blog   color   使用   art   re   

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

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