Friday, July 6, 2007

Placement New


This is not a new subject. Many of us knows this. Many not knows.
Placement new means we can ask the new operator to allocate from a particular memory area. This can be useful when implementing memory pools , to avoid fragmentation of memory.

This is the way to do this.

// Our mem pool of size 1000 bytes.
unsigend char *pMemPool = new unsigned char [1000]; // 1000 bytes is a sample ,use large numbers here.

Now i can ask new to allocate to pMemPool like this

Someclass *p = new (pMemPool) new Someclass;

When comparing the p and (Someclass *) pMemPool reveals they are equal. Don't free p, it will delete whole memory pool ( pMemPool). So allocate as much possible to this memory pool, later we can delete the whole pool . This helps to avoid memory fragmentation.

No comments: