Saturday, May 31, 2008

What is placement new in C++?

  • In some scenarios it becomes necessary to place objects at specified locations in memory. Placement new solves this problem.
  • For example, there could be predefined memory pools in which certain objects need to be placed on creation.
  • Placement new is achieved by overloading the new operator which takes more than one argument apart from the default size_t argument.

Demonstrate the usage of placement new

#include <iostream>
using namespace std;

class MyClass {

    // Placement new operator
    void* operator new (size_t sz, void* v) {
        cout << "Placement new invoked" << endl;
        return v;

    ~MyClass() {
        // Cleanup

int main()
    // Create a buffer to store the object
    int buffer[16];
    cout << "Starting address of my buffer = " << &buffer << endl;

    // Create the object. Use placement new
    MyClass* obj = new (buffer) MyClass();
    cout << "Location of my object = " << obj << endl;

    // Don't delete object created with placement delete
    // Call the destructor explicitly
Starting address of my buffer = 0012FF4C
Placement new invoked
Location of my object = 0012FF4C


  1. The Usage of placement new is correct.
    But we should not call delete on the object, which was allocated through placement new.

    If needed call the destructor explicitly and free the memory you have allocated separately.

    Here in the above example, the memory is automatic/stack memory. So do not delete it explicitly.And no need to call the destructor also.

    1. hey hi can u say that the memory in this example is stack memory. Did you mean the pointer to object created in example is allocated memory at compile time? please reply. also mention what purpose of void pointer v (void *v) in operator function parameter. Please help.

  2. Hi Amar.

    Good comment. The code is fixed now. Agreed it is not correct to call "delete obj" on a object created via placement new.


  3. invalid suffix "FF4C" on integer constant


Contact Form


Email *

Message *

Back to Top