Placement new:

That is a way of separating a constructor from the memory allocation.
When you call new, two things happen: the right amount of memory is
allocated, and the correct constructor is called. That is:

MyObject p = new MyObject;

Allocates enough memory to fit MyObject in, and calls
MyObject::MyObject().

BYTE mem[500];
new (&mem) MyObject;

Does not allocate memory, but calls MyObject::MyObject() using the
address of mem as "this".

I find that it is very rarely needed. There are two cases where I use
it:

1) We have some old code (that for political reasons can't be replaced)
that uses C-style calls, and worse, calls memset() on memory after it is
allocated. If someone were to put a class in that structure, it would be
wiped out, so I use a placement new to force the constructor to be
called. It is a complete hack.

2) I have a piece of shared memory between two applications. The memory
is allocated using a Windows call that just returns a block of memory. I
use placement new to change the BYTE array into a class.




Reply via email to