Corresponding forms of new and delete

From: Dave (better_cs_now_at_yahoo.com)
Date: 10/20/03


Date: 20 Oct 2003 17:11:51 -0400


Hello all,

In the code below, I see the following output:

base::operator new(size_t, int)
base::base()
base::~base()
base::operator delete(void *)

In the case of an exception being thrown during construction, a form of
delete with a signature that corresponds to that of the "new" being used
will be called. However, during a "normal" deallocation, there is no way to
know which version of "new" was previously used, so the usual deallocation
routine is used (I hope I'm using the term "usual" properly here). This is
demonstrated in the output shown above.

When the statement "delete ptr;" is reached, is there a way to cause it to
use "operator delete(void*, int)" as the underlying deallocation routine
rather than "operator delete(void *)"? After all, the usual dellaocation
routine may not do what's right given that the memory was not allocated with
the usual allocation routine! (Again, I hope I'm using the term "usual"
properly.)

I am aware that I could do the following in place of "delete ptr;":

ptr->~base();
base::operator delete(ptr, 243);

However, the point of this article is to see if there is a way to do what I
desire without using explicit calls to the destructor or "operator delete".

Thanks,
Dave

#include <iostream>

using namespace std;

struct base
{
   base()
   {
      cout << "base::base()" << endl;
   }

   ~base()
   {
      cout << "base::~base()" << endl;
   }

   void *operator new(size_t size)
   {
      cout << "base::operator new(size_t)" << endl;
      return ::operator new(size);
   }

   void *operator new(size_t size, int)
   {
      cout << "base::operator new(size_t, int)" << endl;
      return ::operator new(size);
   }

   void operator delete(void *ptr)
   {
      cout << "base::operator delete(void *)" << endl;
      ::operator delete(ptr);
   }

   void operator delete(void *ptr, int)
   {
      cout << "base::operator delete(void *, int)" << endl;
      ::operator delete(ptr);
   }
};

int main()
{
   base *ptr(new(243) base);

   delete ptr;

   return 0;
}

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated. First time posters: Do this! ]