Devs.site

Overrload the "new" and "delete" operators

There's yet another nice feature of the C++ language that deserves to be remembered. Sometimes you go so deep with the development of your classes that you want or need to create a garbage collector or improve the performance of your application in any other way possible. You may also need to get a deeper insight of how the memory is used and need to create some detailed statistics for that


When you create a new object from a class, you do this:

    class Doggie {
    public:
        Doggie();  // this is the constructor
        ~Doggie(); // this is the destructor
    };

    Doggie *goodboy = new Doggie;

The new keyword will take care of allocating memory and calling the constructor. You do your initialization stuff inside the constructor but you can also interfere with the memory allocation phase that takes place before, by overriding the new operator, which takes care of this part

    void* operator new(size_t);

The size_t argument specifies the amount of memory space that needs to be allocated. The same works for the memory freeing phase, which you will possibly need, too, if overriding the new operator (which has the pointer to the allocated memory block as argument).

    void operator delete(void*);

Code

The class declaration:

    class Doggie {
    public:
        Doggie();  // this is the constructor
        ~Doggie(); // this is the destructor
        void* operator new(size_t); // will be overridden
        void operator delete(void*); // will be overridden
    };

and the overridden operators definitions // allocating memory void Doggie::operator new(size_t size) { void memory = malloc(size); cout << "Object memory allocated" << endl; return memory; }

    // freeing memory
    void* Doggie::operator delete(void* ptr)
    {
        cout << "Object memory freed" << endl; 
        free(ptr); 
    }

Requirements


Instructions

Just copy the definition and declaration of the overridden operators and adapt them according to your needs

0 comments

Specify your e-mail if you want to receive notifications about new comments and replies