--slightly reordering your quotes here--
so if i want to allocate a general purpose memory pool |
Just to clarify... there is no reason to do this. The heap is already a general purpose memory pool. You might as well just use it directly (ie: just do a normal new/delete). Throwing everything in a common memory pool gives you zero benefit and is purely disadvantageous.
So the number of sectors is equivalent to the number of objects i want, and the sector size is the size of a single object |
Ideally, yes. Though it might be possible for an object to span several sectors. It depends on how flexible you want your pool to be.
Sector size gives a direct tradeoff between optimal memory usage and potential for memory fragmentation. IE: larger sectors = more wasted memory, but less possibility for fragmentation. Smaller sectors = less wasted memory, but greater risk for fragmentation.
This is exactly why creating a general purpose memory pool is ill-advised. Striking the correct balance is difficult... and you are extremely unlikely to outperform the heap as far as generic memory management goes.
and if i want to access a single object in the pool i just access sector "x" and cast that memory location into a pointer to the type of object i want. |
Well again.. the pool is not accessing objects. It's only distributing memory. I think you might be confusing the two.
The pool will
never need to access an object in the pool. And code outside the pool will
never need to know that the object exists in a pool.
It works like this:
1) main program calls some kind of 'allocate' function in the pool, telling it how much memory it needs
2) The pool find an available sector (or sectors) large enough to contain that memory
3) It marks those sectors as "occupied" so they don't get allocated to other areas
4) It returns a pointer to the start of the sector back to the main program
5) The main program now has a pointer. It can now construct the object of whatever type it needs at that pointer (with placement new).
6) When the main program is done with the object, it calls its destructor
7) Then it sends the pointer it has back to the memory pool, telling it to free the memory
8) The memory pool takes that pointer, figures out which sector(s) it corresponds to, and marks those sectors as "unoccupied" so they can be used again.
then the size of each sector must be at least the size of the largest object and can be arbitrarily big as long as the largest object can fit? |
No, sector size can be smaller than the object size. But then you have to find contiguous sectors, which reintroduces the possibility for fragmentation. ...delicate balance...