2

The std::shared_ptr of C++ comes with a constructor that takes a custom allocator and deleter for the shared_ptr:

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

However the class itself doesn't know about template parameters for the same purpose. Most other template classes in the standard library have a template parameter for allocators. Why doesn't shared_ptr have the same?

Reason I am asking: I want to have a custom heap implementation to be used with all my standard library classes and the shared_ptr sticks out a bit due to it only taking the parameter in the constructor.

Arne
  • 2,624
  • 3
  • 24
  • 45
  • 1
    `std::shared_ptr` implements type-erased deleters. This adds some overhead (basically, a virtual function call) but makes the class template more flexible. Given that `std::shared_ptr` already has some overhead due to reference counting, type-erasure flexibility is acceptable for most users. – Evg Jun 21 '21 at 11:48
  • `std::unique_ptr` has no paramter for allocator either, but it does have the `Deleter` as template parameter. – 463035818_is_not_an_ai Jun 21 '21 at 11:51
  • @463035818_is_not_a_number -- `std::unique_ptr` doesn't allocate anything, so there is no reason for it to have an allocator. – Pete Becker Jun 21 '21 at 13:22

0 Answers0