C++ - What is the placement new operator?

The placement new operator constructs a C++ object in a preallocated block of memory.


Placement new can be significantly faster than the standard new operator. Since placement new works with preallocated memory, it can be used to eliminate out of memory errors in critical code paths.



  #include <malloc.h>
  #include <string>
  
  using std::string;
  
  int main()
  {
      void* memory = malloc(1024); // more than we need!
      
      string* pstr = new(memory) string("hello");
      pstr->~string(); // explicit destructor call
  
      free(memory);
  
      return 0;
  }
  

The standard new operator does 2 things:
  1. Allocate memory
  2. Construct object

Placement new allows you to separate allocation and construction.


Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath