What new kind of functionalities (for debugging or not) do you find helpful by overriding the new operator?
views:
158answers:
5Well, custom memory management and debugging. That's about it, and all you can get out of it too.
The main reason I've had to overload new
has been for performance. One example is allocating a large number of small objects, which is often fairly slow with a general purpose allocator, but can often be improved a lot with a custom allocator.
You might be developing a library that requires some extra stage in initializing certain objects, overloading allows you to do that without some clunky extra calls that the user would otherwise end up having to type.
If you're working with SSE / SIMD, you generally need your memory to be 4-word-aligned, so you might overload new
for the relevant classes to use memalign()
(whereas the default new
is doing something equivalent to plain malloc()
).
There are many cases when overriding operator new must be done. As someone said, it's mainly for custom memory management.
The main example that I've personally dealt with was for embedded systems.
In an embedded system, dynamic memory allocation is usually a problem. Even if you have an embedded operating system that supports it, you have all sorts of issues you might have to deal with (for example, embedded systems often need to be more deterministic than their PC counterparts. Also, you might be working on a system that is supposed to be up for years at a time, in which case memory fragmentation is a real problem).
Because of this, embedded systems tend to disallow dynamic memory allocation completely.
Of course, in most software projects you need some form of dynamic memory, and in those cases you generally implement your own (i.e., have some kind of memory pool that all the threads can ask for memory from, etc).
To make C++ projects use this hand-rolled dynamic memory allocation in the easiest way, I've seen projects override operator new to use the project's allocation method.