
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Placement new operator 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
#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
- Related Articles
- What is the use of "placement new" in C++?
- What uses are there for “placement new” in C++?
- Difference between "new operator" and "operator new" in C++?
- The new operator in Java
- The new operator in JavaScript
- new and delete operator in C++
- What is 'new' Operator in JavaScript?
- Create class Objects in Java using new operator
- Creating JavaScript constructor using the “new” operator?
- How to create JavaScript objects using new operator?
- How to initialize memory with a new operator in C++?
- Matplotlib colorbar background and label placement
- What is Private Placement of Shares?
- What is the difference between new operator and object() constructor in JavaScript?
- When to use new operator in C++ and when it should not be used?
