Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you overload operator new? [duplicate]

Possible Duplicate:
Any reason to overload global new and delete?

In what cases does it make perfect sense to overload operator new?

I heard you do it in a class that is very often allocated using new. Can you give an example?

And are there other cases where you would want to overload operator new?

Update: Thanks for all the answers so far. Could someone give a short code example? That's what I meant when I asked about an example above. Something like: Here is a small toy class, and here is a working operator new for that class.

like image 947
Frank Avatar asked Jan 31 '10 15:01

Frank


3 Answers

Some reasons to overload per class
1. Instrumentation i.e tracking allocs, audit trails on caller such as file,line,stack.
2. Optimised allocation routines i.e memory pools ,fixed block allocators.
3. Specialised allocators i.e contiguous allocator for 'allocate once on startup' objects - frequently used in games programming for memory that needs to persist for the whole game etc.
4. Alignment. This is a big one on most non-desktop systems especially in games consoles where you frequently need to allocate on e.g. 16 byte boundaries
5. Specialised memory stores ( again mostly non-desktop systems ) such as non-cacheable memory or non-local memory

like image 93
zebrabox Avatar answered Oct 30 '22 11:10

zebrabox


Some reasons to overload operator new

  1. Tracking and profiling of memory, and to detect memory leaks
  2. To create object pools (say for a particle system) to optimize memory usage
like image 24
Extrakun Avatar answered Oct 30 '22 10:10

Extrakun


The best case I found was to prevent heap fragmentation by providing several heaps of fixed-sized blocks. ie, you create a heap that entirely consists of 4-byte blocks, another with 8 byte blocks etc.

This works better than the default 'all in one' heap because you can reuse a block, knowing that your allocation will fit in the first free block, without having to check or walk the heap looking for a free space that's the right size.

The disadvantage is that you use up more memory, if you have a 4-byte heap and a 8-byte heap, and want to allocate 6 bytes.. you're going to have to put it in the 8-byte heap, wasting 2 bytes. Nowadays, this is hardly a problem (especially when you consider the overhead of alternative schemes)

You can optimise this, if you have a lot of allocations to make, you can create a heap of that exact size. Personally, I think wasting a few bytes isn't a problem (eg you are allocating a lot of 7 bytes, using an 8-byte heap isn't much of a problem).

We did this for a very high performance system, and it worked wonderfully, it reduced our performance issues due to allocations and heap fragmentation dramatically and was entirely transparent to the rest of the code.

like image 21
gbjbaanb Avatar answered Oct 30 '22 10:10

gbjbaanb