How to Overload new & delete Operators in C++?

Sometimes programmer need to modify the default behaviors of new and delete operators in a customized way. In such cases, these operators can be overloaded to handle memory resources and to increase the efficiency of memory management. Also memory leaks can be detected by overloading new and delete operators. The operator function for new and delete have the following form:

class class_name{
//……
public:
void *operator new(size_t);
void *operator delete(void*);
void *operator new[](size_t);
void *operator delete[](void*);
};

Member operator new() and operator delete() are implicitly static member. So , they don’t have this pointer and do not modify an object. Their purpose is memory allocation and de-allocation. For example:

#include<iostream>

#include<cstdlib>

using namespace std;


class CPoint{

    private:

        int x;

        int y;

    public:

        CPoint(){}

        CPoint(int a, int b):x(a), y(b) {}

        void *operator new (size_t size);

        void *operator new [] (size_t size);

        void operator delete (void *ptr);

        void operator delete[](void *ptr);

        void display();

};


void CPoint::display(){

    cout<<"("<<x<<","<<y<<")"<<endl;

}

void *CPoint::operator new(size_t size){

    cout<<"Overloaded operator new called" <<endl;

    CPoint *ppoint = :: new CPoint;

    return ppoint;

}


void *CPoint::operator new [](size_t size){

    cout<<"Overloaded operator new [] called"<<endl;

    CPoint *ppoint=::new CPoint[size/sizeof(CPoint)];

            //avoid memory leak: size=sizeof(CPoint)*n

    return ppoint;

}


void CPoint::operator delete(void *ptr){

    cout<<"Overloaded operator delete called"<<endl;

    ::delete (CPoint*) ptr;

}


void CPoint::operator delete[](void *ptr){

    cout<<"Overloaded operator delete[] called"<<endl;

    ::delete[] (CPoint*) ptr;

}


int main(){

    CPoint *p1, *p2;

    p1=new CPoint(2,3);

    p2=new CPoint[5];

    cout<<"Value of PI: ";

    p1->display();


    for(int i=0; i<5; ++i){

        p2[i]=CPoint(i+1,i+i);

    }


    for(int i=0; i<5; ++i){

        p2[i].display();

    }

    delete p1;

    delete[] p2;

    return 0;

}
SHARE How to Overload new & delete Operators in C++?

You may also like...

Leave a Reply

Your email address will not be published.

Share