Overloaded instance of C++ 's CNoTrackObject class and new delete operator

  • 2020-04-02 02:53:30
  • OfStack

This article illustrates the overloading of the CNoTrackObject class and the new delete operator in C++. The details are as follows:

Header:

class CNoTrackObject{  
public: //In this case, public is not added as the private variable of the class by default, and MyThreadData cannot access the member variable & NBSP; after inheriting this class. < br / >     void* operator new(size_t nSize); 
    void operator delete(void*); 
    virtual ~CNoTrackObject(){} 
};

The implementation method is as follows:

void* CNoTrackObject::operator new(size_t nSize)  

    //Request a piece of memory & NBSP; < br / >     void* p = ::GlobalAlloc(GPTR , nSize); 
    return p; 

 
void CNoTrackObject::operator delete(void* p) 

    if (p != NULL) 
    { 
        ::GlobalFree(p); 
    } 
}

The use process is as follows:

struct MyThreadData:public CNoTrackObject  

    MyThreadData* pNext; 
    int nShortData; 
}; 
for (int i=0;i<10;i++) 
    { 
        <span style="color:#ff0000;">pData = new MyThreadData;</span> 
        pData->nShortData = i; 
        list.AddHead(pData); 
    } 
 
    //Traversing the list, releasing the space occupied by the MyThreadData object. < br / >     pData = (MyThreadData*)list.GetHead(); 
    while(pData != NULL) 
    { 
        MyThreadData* pNextData = pData->pNext; 
        printf("The value is %dn",pData->nShortData); 
        <span style="color:#ff0000;">delete pData;</span> 
        pData = pNextData; 
    }

     
Hope that the article described in the C++ programming to help you


Related articles: