Creating Objects in Preallocated Memory

We can use the new location to create an object in previously allocated memory.

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 created two objects in a pre-allocated buffer. Are two objects arbitrarily created in the buffer or created in adjacent blocks of memory? If we continue to create more objects in the buffer and want them to be stored in adjacent blocks of memory, what should we do? First create an array in the buffer, and then create each object in the slots of the elements of the array?

+7
source share
2 answers

Both objects are created in the same memory location, namely buf . This is undefined behavior (unless the objects are PODs).

If you want to select multiple objects, you need to increase the pointer, for example. buf + n * sizeof(MyObject) , but beware of alignment issues

Also remember to call destructors when done.

+5
source

The following line of code:

 string *p = new(adr) MyObject(); 

will create a MyObject at adr. Then the next time you create another object, you will find out that the memory in adr is used by the first object, so your next object should be created in adr + sizeof(MyObject) :

 string *q = new(adr + sizeof(MyObject)) MyObject(); 

The point of preallocated memory is such that you do not allocate it at run time, which is pretty slow. You make one big selection at the beginning of the loop / program, and then you just need to use pieces of that selection. The downside is that you have to manage your own memory, which means you need to figure out where to put your objects, which become complex when your memory pool is fragmented!

+3
source

All Articles