PDA

View Full Version : Overriding global new



branko
13th October 2010, 09:56
Hello all,
I would be most grateful for your help. What I want to do in my application is to override new and delete not just for one class, but for the entire application. C++ allows you to do that by defining global versions of these operators. Here’s how I override global new and delete:
void* operator new (size_t size)
{
void *p = malloc(size);
return p;
}

void operator delete (void *p)
{
free(p);
}
The behavior I am facing after I have overridden global new and delete in this way is that at the beginning of the application (initialization that takes place before the event loop has been started) the overridden new is being invoked on some objects (not all), but after the event loop has started there is no invocation of the overridden new operator although there are objects that are dynamically created.
I would appreciate any suggestions on this issue.
Regards,

SixDegrees
13th October 2010, 10:34
Qt does it's own internal memory management, making use of smart pointers, copy-on-change and many other customized memory allocations/deallocations. You can dig around in the source code, or search on "Qt Memory Management" on Google, but the short answer is that Qt almost certainly isn't going to honor your modified new() and delete() operators because it implements it's own versions that will override yours.

Generally, overriding new() and delete() is considered bad programming practice, and conflicts like these are only one example of the problems it can cause. If you're going to do custom memory management, you should just do it, using your own routines, rather than overriding routines that are expected to have certain behavior. Same applies to the Trolls, who should also avoid such practices imho.

branko
19th October 2010, 16:10
Hi,
Thank you for your reply. There is one thing I would like to know: Does Qt's new operator returns 0 on unsuccessful memory allocation or it throws bad_alloc memory exception?
Regards,