We can use placement new to create an object in pre-allocated memory.
Let’s consider the following example:
char *buf = new char[1000]; //pre-allocated buffer
string *p = new (buf) MyObject(); //placement new
string *q = new (buf) MyObject(); //placement new
I’ve created two objects in the pre-allocated buffer. Are the two objects created randomly within the buffer or created in contiguous memory blocks? If we keep creating more objects in the buffer and want them to be stored in contiguous memory blocks, what should we do? Create an array in the buffer first and then create each object in the element slots of the array?
The two objects are both created at the same memory location, namely
buf. This is undefined behaviour (unless the objects are POD).If you want to allocate several objects, you have to increment the pointer, e.g.
buf + n * sizeof(MyObject), but beware of alignment issuesAlso don’t forget to call destructors when you’re done.