C++提前delete

时间:2023-01-17 07:29:48
 //////////////////////////////////////
 ///类析构以后,成员变量内存空间释放,
 ///函数 和 变量 还是可以引用的
 //////////////////////////////////////
 #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();
     ); return m_ptr;}
     int* getPtr(){ return m_ptr; }
     void setPtr2(int* p2) { m_ptr2 = p2;}

 private:
     int        m_refCount;
     int*    m_ptr;
     int*    m_ptr2;
 };

 CTest::CTest()
 {
     m_refCount = ;
     m_ptr = NULL;
 }
 CTest::~CTest()
 {
     m_refCount = ;
     delete m_ptr;//new的内存需要delete释放, 不然内存泄露。 系统只给指针值清空
 }

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

 void CTest::ReleaseRef()
 {
     --m_refCount;
     Print();
     )
     {
         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();
     }*/
     int *a = NULL;
     a = ct->setPtr();
     cout<<"&a1 = "<<a<<endl;
     cout<<"a1 = "<<(*a)<<endl;

     );
     ct->setPtr2(b);
     delete ct;
     cout<<"m_ptr = "<<(ct->getPtr())<<endl;
     cout<<"&a1 = "<<a<<endl;
     cout<<"a1 = "<<(*a)<<endl;

     cout<<"b = "<<*b<<endl;
     ct->Print();
     //ct->ReleaseRef();
     ct->Print();

     system("pause");
     ;
 }