I have a region of memory, which will be used for multiple queues. For example, I allocate 1024 bytes of memory and I need two queues. The first queue will occupy the first 512 bytes and the second the next 512 bytes.
However, my queue is represented by a C++ class. Using the placement new operator, how can I construct each queue object. Is the following approach correct?
Queue *q1, *q2;
void *mem = malloc( 1024 );
*q1 = new (mem) Queue;
*q2 = new (mem+512)Queue;
I would do the following:
If it’s important that the two queues are exactly 512 bytes from each other your original suggestion is almost correct:
This assumes
sizeof(Queue) <= 512. The reason for the cast tochar*is that pointer arithmetic withvoid*is illegal in C++.