Posts tagged construct objects
Construct C++ objects at predefined Memory Locations.
0![]()
Usually we use new operator to allocate objects. The new operator will allocate memory for object and calls the object’s constructor. We can construct our object in predefined memory location by using Placement new.
![]()
In placement new, you can pass the preferred memory location to the new operator at which the object to be constructed. During placement new, the new operator just calls the constructor. Responsibility of memory allocation is ours. After usage we should call the destructor manually to delete the object. Please see the following code block about usage of placement new.
// Allocate memory ourself char* pMemory = new char[ sizeof(MyClass)]; // Construct the object ourself MyClass* pMyClass = new( pMemory ) MyClass(); // TODO: Use pMyClass and enjoy!!! // The destruction of object is our duty. pMyClass->~MyClass();
![]()
The advantages of placement new are as follows -
1) Can allocate a pool of memory and construct objects on our wish.
2) This prevents memory allocation failure fear in runtime, because pool of memory is already allocated.
3) Object creation will be a bit faster, because memory is already allocated and only the constructor is to be called.
4) Since you can place your objects at your preferred memory locations, its very useful in embedded programming. For instance the hardware may be placing 255 bytes of data at memory location – 0×1000. In that case, write a class with an array of 255 Bytes as member variable and construct the object at 0×1000. Now you can access the data by using that object.
And one more interesting bit of information – The placement new is the only scenario in which we are legally allowed to call destructor explicitly as per C++ standards. The “New” New informations are interesting… isn’t it?

Targeted Audience – Intermediate.