I wrote a basic custom memory management allocator which would grab a chunk of memory, pre-create X objects so that whenever I needed to "create" an object I could grab one of the pre-created ones and simply assign data members (memory was already allocated).
I used placement-new
:
//Grab a chunk of memory
char* buf = new char [sizeof(X) * num_objs];
//Pre-create a lot of objects
for(std::int64_t i=0; i<num_objs; i++){
char* c = buf + (sizeof(X) * i);
//This line creates the Order object at location c
X* x = new(c)X;
}
//Assign data members to objects
for(std::int64_t i=0; i<num_objs; i++){
char* buf_loc = buf + (sizeof(X) * i);
X* my_x = reinterpret_cast <X*> (buf_loc);
my_x->a = 1;
my_x->b = 2;
my_x->c = 3;
my_x->d = 4;
}
How easy/practical would it be to change the above and directly grab memory from the OS using brk()
?