Search code examples
c++new-operatorplacement-new

Destroy call in placement new


I have a basic question.

Generally, using placement new, we could construct the object on the preallocated memory.

Say for an example: My_CLass size is 20 Bytes and want to create a pool for 5 objects. So 5*20 => 100 bytes have been allocated and the starting address of the pool is 0x1234

Now, using placement new, i have placed 3 object in the memory pool.

My question is,

  1. Having that starting address 0x1234, Is there anyway to find the number of valid objects in the pool?

  2. If i destroy the second object, how system knows the next object to be created in the second position and so on?


Solution

  • For this discussion, the word "pool" is used to mean some kind of pre-allocated memory supposed to hold a set of objects of some particular kind (could be all one class, or different classes, related or unrelated)

    1. Maybe. It all depends on how the pool itself is designed and implemented.

    2. The pool, assuming a correct and working implementation that supports this sort of operation, will keep track of where free space is located, how big it is, etc.

      The way this often works is that there is a pointer stored in the pool's metadata (in other words, the data about the pool itself, where it is known what size the pool is, how many elements are allocated, etc), which is the head of a linked list of free elements in the pool. This is just ONE solution, but it's a fairly common one.

    Note that there is absolutely no difference between this case and regular new allocating from the heap, except that if you have a specific pool that has the ability to track the number of elements in the pool, which the normal heap won't allow you to do directly (you can most perhaps find out how many allocations there are in total, but that would be anything from file-buffer allocations and dynamic strings to objects of type X, type Y - the heap itself doesn't track what the purpose of a particular allocation is, that's "someone else's problem").