What uses are there for “placement new” in C++?


In this section we will see what is the placement new operator in C++. This placement new is another variation of new operator. The normal new operator performs two things. It allocates memory, and then constructs an object in allocated memory.

The new operator allocates memory in the heap section and constructs objects there. But for the placement new operator, it constructs object at the given address. To deallocate memory, we can use delete keyword if the memory is allocated using new operator. But for placement new there is no placement delete feature.

So 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 given type to be constructed. For example.

Example Code

 Live Demo

#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

a = 5
&a = 0x22fe34
After using placement new:
a = 10
m = 0x22fe34
&a = 0x22fe34

Updated on: 30-Jul-2019

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements