views:

397

answers:

2

Hello everyone, here is a short question :

Using C++, how can I call a constructor on a memory region that is already allocated ?

+17  A: 

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).

Anteru
+3  A: 

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();
Konrad Rudolph
Why should we call the destructor on the newly allocated memory before doing the placement new ? I dont get it...
Malkocoglu
You normally don't get memory that has been allocated but not initialized. If that's indeed what you've got then of course you *must not* call a destructor on it. For all other cases, there is already an object at that location that must be properly disposed of.
Konrad Rudolph