What is placement new operator in C++ ?

Raju Pal

Placement new operator is used to allocate a memory which is already acquired by some object. This operator generally used when we require any object to be re-constructed multiple times. Without placement new operator it will be allocated to different memory location while reconstructed. Hence we use placement new to utilize the memory which is allocated to it earlier.
A simple example for the placement new operator is given following example:


class StudyKoner
{
char SK[100];
int n;
};
char buf1[200];
char buf2[400];

int main()
{
 SK *pa1,*pa2;          // Two pointers of  type class SK
int *pi1,*pi2;          // Twp integer type pointers
pa1=new a;              //placing a class in heap
pi1=new int [10];       //placing the array in heap
pa2=new (buf1) a;       //placing the class in bf1
pi2=new (buf2) int [10];//placing the class in buf2
delete pa1;
delete [ ]pi1;
return 0;
}

In above example we the object of class StudyKorner i.e. pa2 is allocated the memory to same location where character buffer buf1 was allocated.

What do you think about the article?

This site uses Akismet to reduce spam. Learn how your comment data is processed.