[Development] std::allocate_shared for QSharedPointer

Marc Mutz marc.mutz at kdab.com
Tue Oct 3 15:54:08 CEST 2017


On Saturday 09 September 2017 10:46:49 Sean Harmer wrote:
> Hi,
> 
> I have a use case where we need to create, use and destroy a relatively
> large number of QSharedPointers rapidly. To avoid the malloc overhead it
> would be nice to be able to use a pool of QSharedPointers.
> 
> We have QSharedPointer::create() which is analogous to
> std::make_shared() that allows to reduce creating a QSharedPointer and
> the object it points at to a single memory allocation.
> 
> However, this uses operator new internally. I can't see any equivalent
> of std::allocate_shared() which would allow the use of a custom
> allocator for the QSP and object memory allocation.
> 
> Does anybody have any plans to add such a facility? Or is there some
> other facility to avoid operator new here for both the QSP and the
> object itself?

Add the missing aliasing ctor[1] to QSharedPointer, then create a block of 
objects, possibly allocated with alloc_shared, and then hand out child QSPs to 
the elements:

  struct BlockOfFoos { Foo foos[16]; }

  auto block = QSharedPointer<BlockOfFoos>::create();
  for (auto &e : block->foos)
    co_yield QSharedPointer<Foo>{block, &e}; // aliasing ctor

This reduces the overhead to one memory allocation per block, ie. in this 
case, 16-fold.

[1] ctor 8 in http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr

HTH,
Marc

-- 
Marc Mutz <marc.mutz at kdab.com> | Senior Software Engineer
KDAB (Deutschland) GmbH & Co.KG, a KDAB Group Company
Tel: +49-30-521325470
KDAB - The Qt, C++ and OpenGL Experts



More information about the Development mailing list