C + + CNoTrackObject class and overloaded instance of the new delete operator _c language

Source: Internet
Author: User

This article describes the CNoTrackObject class in C + + and the new delete operator overload, shared for everyone to reference. Specifically as follows:

Header information:

Copy Code code as follows:
Class cnotrackobject{
Public://Here is the fault, no add public default is a private variable for the class, and Mythreaddata cannot access the member variable after inheriting this class
void* operator new (size_t nsize);
void operator Delete (void*);
Virtual ~cnotrackobject () {}
};

The implementation method is as follows:

Copy Code code as follows:
void* cnotrackobject::operator New (size_t nsize)
{
Request a piece of memory
void* p =:: GlobalAlloc (Gptr, nsize);
return p;
}

void Cnotrackobject::operator Delete (void* p)
{
if (P!= NULL)
{
:: GlobalFree (P);
}
}

The use process is as follows:

Copy Code code 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, freeing the space occupied by the Mythreaddata object
PData = (mythreaddata*) list. GetHead ();
while (PData!= NULL)
{
mythreaddata* Pnextdata = pdata->pnext;
printf ("The value is%d\n", pdata->nshortdata);
<span style= "color: #ff0000;" >delete pdata;</span>
PData = Pnextdata;
}



I hope this article will help you with the C + + program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.