What is the use of "placement new" in C++?


In a nutshell, placement new allows you to "construct" an object on memory that's already allocated to a given variable. This is useful for optimizations as it is faster to not reallocate and reuse the same memory that is already assigned to it. It can be used as follows −

new (address) (type) initializer

We can specify an address where we want a new object of the given type to be constructed. 

Example

#include<iostream>
using namespace std;
int main() {
   int a = 5;
   cout << "a = " << a << endl;
   cout << "&a = " << &a << endl;

   // Placement new changes the value of X to 100
   int *m = new (&a) int(10);

   cout << "\nAfter using placement new:" << endl;
   cout << "a = " << a << endl;
   cout << "m = " << m << endl;
   cout << "&a = " << &a << endl;

   return 0;
}

Output

This will give the output −

a = 5
&a = 0x60ff18

After using placement new −

a = 10
m = 0x60ff18
&a = 0x60ff18

Updated on: 24-Jun-2020

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements