How to overload global new and delete in c++. We can overload new and delete operators globally. These operators also can be overloaded on class by class basis and we know this facts in c++.

Simple example to overload global new and delete in c++

#include<iostream>
#include<malloc.h>
using namespace std;

void *operator new(size_t s) {
	cout << "Allocating memory\n";
	void *mem = (void*) malloc(s);
	return mem;
}

void operator delete(void *addr) {
	cout << "freeing memory\n";
	free(addr);
}

int main() {
	int *s = new int;
	*s = 2;
	cout << *s << endl;
	delete s;
	return 0;
}

OUTPUT:

Allocating memory
2
freeing memory

Use case for overloading global new and delete in c++

How to prevent global overloading of new and delete in c++

#include<iostream>
#include<malloc.h>
using namespace std;

void * operator new(std::size_t s) throw (std::bad_alloc) {
	return NULL;
}
void operator delete(void * mem) throw () {
}

int main() {
	int *s = new int;
	if (s) {
		*s = 2;
		cout << *s << endl;
		delete s;
	}
	return 0;
}

In the above program we have replaced overloading of new and delete. So if we would compile above program it will compile successfully but there would be no output.



Related Contents to follow