Valhalla Legends Forums Archive | Advanced Programming | Overloading new

AuthorMessageTime
Arta
Is it possible to overload new at global scope and still call the original new from within that function?

Something like:

[code]
void *operator new(size_t Size)
{
   void *Ptr = ::operator new(Size);

   if(!Ptr)
   {
      // Memory allocation failed
      Output(MSG_FATAL, "Insufficient memory!\n");

      ExitProcess(0);
   }

   return Ptr;
}
[/code]

...except that doesn't recurse.
February 18, 2004, 4:07 PM
Eibro
What are you trying to do? Provide extra handling if allocation fails? If so, see std::set_new_handler().
February 18, 2004, 6:48 PM
Arta
Ah, excellent. Thanks.
February 18, 2004, 7:29 PM
Skywing
I'd use something else, like malloc or HeapAlloc. No scoping tricks needed there.

You could also use the throwing new with exception handlers, as a possible alternative to set_new_handler if this fits your program better.
February 19, 2004, 6:58 AM
Arta
is it safe to [color=blue]delete[/color] memory allocated with malloc? Pretty sure it is, but would like to confirm :)
February 19, 2004, 8:54 AM
Yoni
[quote author=Arta[vL] link=board=23;threadid=5351;start=0#msg45012 date=1077180870]
is it safe to [color=blue]delete[/color] memory allocated with malloc? Pretty sure it is, but would like to confirm :)
[/quote]
No :)
Standard C++ says you can't mix them.

Maybe you can in specific compilers as an extension.
February 19, 2004, 5:52 PM
iago
I still remember a classic:

HashTable::~HashTable()
{
delete table;
free(position);
}

.. or something very similar to that. It was about there that we scrapped it and started over :)
February 19, 2004, 6:02 PM
Skywing
[quote author=Arta[vL] link=board=23;threadid=5351;start=0#msg45012 date=1077180870]
is it safe to [color=blue]delete[/color] memory allocated with malloc? Pretty sure it is, but would like to confirm :)
[/quote]
No. It's also not safe to delete memory allocated with new[]. Note that this is even true with VC - usually, if you mix the two, you'll cause heap corruption (at best) or crash immediately (at worst).

If you are overloading operator new, you should probably also overload operator delete.
February 19, 2004, 6:19 PM
Arta
In which case, my original question stands. How do I avoid the scoping issue? Just curious now :)
February 19, 2004, 8:22 PM

Search