35. Placement New

Question.6

A firmware engineer combines placement new with a fixed pool to create/destroy Packet objects. What technique is this?

alignas(Packet) uint8_t pool[MAX][sizeof(Packet)];
bool used[MAX] = {};

Packet* alloc(int id) {
   for (int i = 0; i < MAX; i++)
       if (!used[i]) {
            used[i] = true;
            return new (pool[i]) Packet(id);
       }
   return nullptr;
}

void release(Packet* p) {
   if (!p) return;

   p->~Packet();  // explicit destructor

   size_t index = (reinterpret_cast<uint8_t*>(p) -
                   reinterpret_cast<uint8_t*>(pool)) / sizeof(Packet);

   used[index] = false;
}
Need Help? Refer to the Quick Guide below

Select Answer

Restart quiz!