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;
}
Placement new allows you to separate allocation and construction.