4 ms·
C++ allows both overriding (i.e., replacing) and overloading (i.e., creating multiple versions of) operator new. When overriding, you still have to call some m
by maxlybbert 13y ago
C++ allows both overriding (i.e., replacing) and overloading (i.e., creating multiple versions of) operator new. When overriding, you still have to call some memory allocation routine; and you should also override operator delete, and should probably override operator new[]/operator delete[]. There are some pitfalls in doing this on some platforms ( http://pavlovdotnet.wordpress.com/2008/01/12/jemalloc-builds/ http://pavlovdotnet.wordpress.com/2008/01/12/jemalloc-builds... ).
The tricky part, to me at least, is when overloading. It's possible to overload new in a way that "new int" calls the original new, and "new int, foo" calls your overloaded allocator (foo could be an object used for the sole purpose of knowing which new to call, or it could actually be used by that new -- maybe it's a memory pool). That's easy enough to do. The surprise comes from the fact that while you can overload operator delete, it's a real pain to call the overloaded version (plus, of course, you have to remember which memory came from which version of new). Assuming you use "foo" to specify your overloaded new and delete, "delete p, foo" is a syntax error. You need to call something like "::operator delete(p, foo)". At least that was the case with C++03; I don't know if C++11 changed anything. Personally, I just overload new, but call a destroy() function instead of an overloaded delete.