Monday, January 28, 2008

Displacement new operator in C++

Have you ever seen C++ code like this?

void *spc = memPool->Alloc(sizeof(ObjectC));

ObjectC * content = new (spc) ObjectC();

This is really hard-to-read code for many beginners. It looks this piece of code couldn't even pass the symtax check.

This is called "placement new". That is, the first line allocate the memory block at a specific location in memory (which should you implement in the Alloc() method of your memory pool object). The second lilne takes the pointer to the allocated memory block as a parameter to new operator (yes, new operator could take a parameter). So new will use this memory block to place the new object, instead of allocating by itself. This way, the new object is allocated at a specific location.

Why you can't directly do this way?

ObjectC * content = (ObjectC *) memPool->Alloc(sizeof(ObjectC));

Since then the constructor is not called. You should NEVER allocate a new object by simple allocate memory for it.

That's a special symtax for new. Last thing is: try not to use thi symtax unless you really need it. If you use this symtax, make sure you always allocate sufficient and correctly aligned memory for the object.

Also, you are responsive for the destruction of this object. Neither compiler nor run-time will take care of that. So, write down the line somewhere after you finished your object:

content->~ObjectC();

No comments: