c++ - How does boost.pool achieve re-use of allocated memory? -
background
my previous question boost.pool led me investigate boost.pool in detail, , have supplementary question finalize understanding.
prelude
this reference states following object pool pattern:
the object pool pattern software creational design pattern uses set of initialized objects kept ready use, rather allocating , destroying them on demand.
from can tell, boost.pool (simplified) implements object pool pattern means of memory allocation , management based on size of element_type, , returns simple pointer allocated object:
element_type * malloc(); void free(element_type * p); a simple boost example shows not necessary explicitly free acquired element:
x * const t = p.malloc(); ... // t; don't take time free() it. question
i understand allocated memory safely freed on destruction of pool object, how pool know when block of memory acquired client has been released pool , reusable if interface hands direct pointer element_type, yet call free() still not required? i.e. how can boost pool re-use memory if cannot memory not still in use? , if not re-use memory, considered same pattern 1 explained wiki reference?
how can boost pool re-use memory if cannot memory not still in use?
it can't. in fact won't reuse memory. guarantee have no leaks when pool destroyed.
and if not re-use memory, considered same pattern 1 explained wiki reference?
the article linked says: object pooling can offer significant performance boost in situations cost of initializing class instance high
while boost pool introduction: pools used when there lot of allocation , deallocation of small objects.
so no, not same pattern. 1 meant re-use objects expensive construct (threads, opengl resources, etc.). other meant manage lot of small objects, giving more control standard allocator gives.
as pointed out, there 2 ways of using pools:
- as allocator, calling malloc()/free() when appropriate. basic pool-allocator usage, helps reduce memory fragmentation
- construct ton of temporary objects , don't bother delete them.
example second case: imagine have graph class, each node stores neighbors using pointers. have make deep copy of graph. allocate bunch of new nodes , copy data old ones new ones, have initialize neighbors pointers, need map old pointers new pointers:
std::map<node*,node*> old_ptr_to_new_ptr; this example pool allocators useful (i won't go detail how use pool allocators std containers): lot of small objects (map nodes) going deleted together.
Comments
Post a Comment