Allocation and deallocation functions (C++ only)

You may define your own new operator or allocation function as a class member function or a global namespace function with the following restrictions:
  • The first parameter must be of type std::size_t. It cannot have a default parameter.
  • The return type must be of type void*.
  • Your allocation function may be a template function. Neither the first parameter nor the return type may depend on a template parameter.
  • If you declare your allocation function with the empty exception specification throw(), your allocation function must return a null pointer if your function fails. Otherwise, your function must throw an exception of type std::bad_alloc or a class derived from std::bad_alloc if your function fails.
You may define your own delete operator or deallocation function as a class member function or a global namespace function with the following restrictions:
  • The first parameter must be of type void*.
  • The return type must be of type void.
  • Your deallocation function may be a template function. Neither the first parameter nor the return type may depend on a template parameter.
The following example defines replacement functions for global namespace new and delete:
#include <cstdio>
#include <cstdlib>

using namespace std;

void* operator new(size_t sz) {
  printf("operator new with %d bytes\n", sz);
  void* p = malloc(sz);
  if (p == 0) printf("Memory error\n");
  return p;
}

void operator delete(void* p) {
  if (p == 0) printf ("Deleting a null pointer\n");
  else {
    printf("delete object\n");
    free(p);
  }
}

struct A {
  const char* data;
  A() : data("Text String") { printf("Constructor of S\n"); }
  ~A() { printf("Destructor of S\n"); }
};

int main() {
  A* ap1 = new A;
  delete ap1;

  printf("Array of size 2:\n");
  A* ap2 = new A[2];
  delete[] ap2;
}
The following is the output of the above example:
operator
new with 40 bytes
operator new with 33 bytes
operator new with 4 bytes
Constructor of S
Destructor of S
delete object
Array of size 2:
operator new with 16 bytes
Constructor of S
Constructor of S
Destructor of S
Destructor of S
delete object