What is an in-place constructor in C++?

Akhil picture Akhil · Sep 21, 2010 · Viewed 37.7k times · Source

Possible Duplicate:
C++'s “placement new”

What is an in-place constructor in C++?

e.g. Datatype *x = new(y) Datatype();

Answer

linuxuser27 picture linuxuser27 · Sep 21, 2010

This is called the placement new operator. It allows you to supply the memory the data will be allocated in without having the new operator allocate it. For example:

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();

After the destructor is manually called, the memory can then be freed as expected.

free(fm);