What’s placement new operator and why do we need it ?

Placement new operator and it’s need

This article is all about placement new operator.

Placement new operator :

placement new operator we use to pass a memory address to new as a parameter. This memory is used by the placement new operator to create the object and also to call the constructor on it and then returning the same passed address.

Need of placement new operator :

As we know when we create any object using new operator, then the memory is allocated on the heap.

int * ptr = new int;

But, while working sometimes we need to create an object dynamically for which some specific memory location will be allocated.

For example, we do not want new memory to be allocated on heap rather it needs to be allocated on a given memory address. Actually this scenario comes when we work on any embedded product or with shared memory. So, for this requirement we use placement new operator.

Below is an example code to achieve this :

// Program

#include <iostream>
#include <cstdlib>
#include <new>

int main()
{
// Here memory will not be allocated on heap.
int * space = new int[1004];
// It will use passed spacer to allocate the memory
int * ptr = new(space) int;
*ptr = 7;
std::cout<<(*ptr)<<std::endl;
delete [] buffer;
return 0;
}