Wednesday 22 February 2012

Explain the use of the placement new method? | Constructor in C++

The placement new method is used to place an object at a particular location in memory. For placing an object to its particular location, it allocates a pointer parameter to a new part of a new expression.
 PROGRAM::
Line #1 creates an array of size of (Tom) bytes of memory, which is big enough to hold a Tom object. Line #2 creates a pointer place and points to the first byte of this memory. Line #3 essentially calls the constructor Tom::Tom (). The this pointer in the Tom constructor will be equal to place. The returned pointer j will therefore be equal to place.
 The sole responsibility of a programmer is to destruct the placed object. To do this, the explicit calling of the destructor is needed:
 void mno()
{
char memory[sizeof(tom)];
void* b = memory;
Bred* j = new(b) Tom();
j>~Tom();
e placed object
}
In the rare scenario like the preceding one, you need to explicitly call the destructor.