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.
[showads ad=inside_post]
To achieve this we use placement new operator,
Frequently Asked:
- Allocating and deallocating 2D arrays dynamically in C and C++
- C++ : How to read or write objects in file | Serializing & Deserializing Objects
- How virtual functions works internally using vTable and vPointer?
- How does new and delete operator works internally ?
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,
#include <iostream> #include <new> #include <cstdlib> int main() { int * buffer = new int[1000]; // Will not allocate new memory on heap. // Will use passed buffer to allocate the memory int * ptr = new(buffer) int; *ptr = 7; std::cout<<(*ptr)<<std::endl; delete [] buffer; return 0; }
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.