How to call a constructor on an already allocated memory?
You can use the placement new constructor, which takes an address.
Foo* foo = new (your_memory_address_here) Foo ();
Take a look at a more detailed explanation at the C++ FAQ lite or the MSDN. The only thing you need to make sure that the memory is properly aligned (malloc
is supposed to return memory that is properly aligned for anything, but beware of things like SSE which may need alignment to 16 bytes boundaries or so).
Notice that before invoking placement new
, you need to call the destructor on the memory – at least if the object either has a nontrivial destructor or contains members which have.
For an object pointer obj
of class Foo
the destructor can explicitly be called as follows:
obj->~Foo();