3

std::shared_ptr internally allocates(::new) a Control Block(Reference Count Object) in heap. When shared ptr's reference count becomes zero this Control block is deallocated(::delete). For Performance reasons I need to re-cycle the memory allocated for this Control Block.

Accepted answer to Question Is an Object Pool pattern of shared_ptr possible?, says a Custom Allocator should do the trick. But it is NOT clear to me how the Allocator (Alloc) object created for Y does the allocation for Control Block

template< class Y, class Deleter, class Alloc > std::shared_ptr( Y* ptr, Deleter d, Alloc alloc );

Could someone please point to an example of a custom allocator written for std::shared_ptr which re-cycles the Control Block object

OR

provide a partial code to re-cycle Control Block

OR

explain how an Allocator<Y> can allocate the Control Block for std::shared_ptr template< class Y, class Deleter, class Alloc >

NOTE : I am looking for a Solution that does NOT use boost::intrusive_ptr

aKumara
  • 395
  • 1
  • 12
  • There will be only one allocated block if you were to use `make_shared`/`allocate_shared`. Stick to those and there will be nothing to recycle. :-) – oakad Feb 21 '21 at 08:09
  • 2
    `shared_ptr` constructor taking an allocator would use [`allocator_traits::rebind_alloc`](https://en.cppreference.com/w/cpp/memory/allocator_traits) to obtain the allocator for some internal type it uses for the control block. – Igor Tandetnik Feb 21 '21 at 13:21
  • the disadvantage there is the managed object will ONLY be deleted when the last weak_pointer is destroyed. There are advantages to keeping the control block as a separate object in which case having a pool of them will be a performance advantage and help prevent memory fragmentation., It would be nice to have two allocator methods one for the control block and one for the object. – peterk Sep 22 '22 at 12:10
  • @IgorTandetnik I have to test this it woudl be great if one can separately manage both the control block and the object allocation methods separately. – peterk Sep 22 '22 at 12:12

1 Answers1

-1

you just need to check out that there's no weak poitnters left (weak reference counter = 0) then do ptr.reset().