码迷,mamicode.com
首页 > 编程语言 > 详细

C++提前delete

时间:2014-11-25 16:22:05      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   os   sp   for   div   

//////////////////////////////////////
///类析构以后,成员变量内存空间释放,
///函数 和 变量 还是可以引用的
//////////////////////////////////////
#include <iostream>
using namespace std;

class CTest
{
public:
    CTest();
    ~CTest();
    void Print() { cout<<"....."<<m_refCount<<endl; }
    void AddRef();
    void ReleaseRef();
    int GetRef() { return m_refCount; }
    void destroy();

private:
    int        m_refCount;
};

CTest::CTest()
{
    m_refCount = 1;
}
CTest::~CTest()
{

}

void CTest::AddRef()
{
    ++m_refCount;
    Print();
}

void CTest::ReleaseRef()
{
    --m_refCount;
    Print();
    if(m_refCount <= 0)
    {
        delete this;
        //return;
        Print();
    }
}

void CTest::destroy()
{
    delete this;
}

int main()
{
    CTest* ct = new CTest;    //一定要声明为指针,不然delete时会报错。
    /*for(int _i = 0; _i < 5; ++_i)
    {
        ct->AddRef();
    }

    for(int _i = 0; _i < 6; ++_i)
    {
        ct->ReleaseRef();
    }*/
    delete ct;
    ct->Print();
    ct->AddRef();
    ct->Print();

    //system("pause");
    return 0;
}

 

C++提前delete

标签:des   style   blog   io   color   os   sp   for   div   

原文地址:http://www.cnblogs.com/felove2013/p/4121147.html

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