- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements