I'm rusty on this one but it allows you to write the object to a memory block you have already allocated. It also needs a reciprocal delete statement to clear it from memory.
If you use a memory pool, then you need to use the in place constructor to initialize your object as they are allocated from the pool.
It's a way to call a constructor without allocating memory. Your y
has to be a pointer poniting to enough memory for a new Datatype object. Also, don't call delete
, call ~DataType()
.
This is call the placement new operator. It allows you to supply the memory the data will be allocated in without having the new
operator allocate it.
Foo * f = new Foo();
The above will allocate memory for you.
void * fm = malloc(sizeof(Foo));
Foo *f = new (fm) Foo();
The above will use the memory allocated by the call to malloc
. new
will not allocate any more. You are not however limited to classes. You can use a placement new operator for any type you would allocate with a call to new
.
A 'gotcha' for placement new is that you should not release the memory allocated by a call to the placement new operator using the delete
keyword. You will destroy the object by calling the destructor directly.
f->~Foo();
This is more commonly known as 'placement new' and is discussed pretty well by the C++ FAQ (in the 'Destructors' area):
It allows you to construct objects in raw memory, which can be useful in certain specialized situations, such as when you might want to allocate an array for a large number of possible objects, but want to construct then as needed because you often might not need anywhere near the maximum, or because you want or need to use a custom memory allocator.