Examples of operators new() and delete()


/************************************************************************
*

The following example shows two overloaded new operator functions.

                                                                        *
************************************************************************/

#include <stddef.h>
class X
{
public:
      void* operator new(size_t);
      void* operator new(size_t, int);
};

void main ()
{
      X* ptr1 = new X;        // calls X::operator new(sizeof(X))
      X* ptr2 = new(10) X;    // calls X::operator
                              // new(sizeof(X),10)
}

/************************************************************************
*

The following example shows the declaration and use of the operator functions operator new() and operator delete():

                                                                        *
************************************************************************/

#include <stddef.h>
class X
{
public:
      void* operator new(size_t);
      void operator delete(void*);         // single argument
};
class Y
{
public:
      void operator delete(void*, size_t); // two arguments
};

void main ()
{
      X* ptr = new X;
      delete ptr;      // call X::operator delete(void*)
      Y* yptr;
// ...
      delete yptr;     // call Y::operator delete(void*, size_t)
                       // with size of Y as second argument
}