what’s placement new operator and why do we need it.
In this article we will discuss what is placement new operator and what’s its need.
Need of placement new operator
Every when we create a new object using new operator, memory is allocated on heap i.e.
int * ptr = new int;
But there might be scenarios when we want to dynamically create an object at some specific memory location.
For example, in embedded devices or at shared memory etc.
In such scenario we don’t want new memory to be allocated on heap, but use a given memory address to create a new object.
To achieve this we use placement new operator,
Placement new operator
In placement new operator we pass memory address to new as a parameter, placement new operator will use this memory to create a new object. It also calls the constructor on it and then returns the same passed address.
Check out this example,
int * buffer = new int;
// Will not allocate new memory on heap.
// Will use passed buffer to allocate the memory
int * ptr = new(buffer) int;
*ptr = 7;
delete  buffer;
We don’t need to delete the object created using placement new operator because no new memory was allocated for it. So, instead of calling delete operator on it, one can call the destructor explicitly if required.
If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.