jeudi 27 août 2020

Cannot make std::reference_wrapper work with std::unique_ptr

I have an object pool that holds objects in std::unique_ptr<T>.

The pool, like most pools, holds objects that are expensive to create, but once an object is borrowed there is no way of preventing an object with the same settings from being added to the pool so I'd like to extend it to prevent that from happening.

I see 3 options for this:

  1. Replace std::unique_ptr<T> with std::shared_ptr<T> but there's no plans to have multithreaded code and this breaks the convention of ownership - the pool should not own an object just to read one of its properties.

  2. Keep a copy of a property of T with the pool in a std::vector, adding and removing when std::unique_ptr<T> is borrowed from and returned to the pool. Easy to implement but feels wrong as I'm duplicating data.

  3. Use a std::vector<std::reference_wrapper<std::unique_ptr<T>>>. By keeping a reference to borrowed std::unique_ptr<T> I have access to its properties and I can easily prevent objects with the same settings from being created.

I'm currently trying to implement 3 but am stuck on how to add a reference to std::unique_ptr<T> to std::vector<std::reference_wrapper<std::unique_ptr<T>>>. Is this even possible?

Aucun commentaire:

Enregistrer un commentaire