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:
-
Replace
std::unique_ptr<T>
withstd::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. -
Keep a copy of a property of T with the pool in a
std::vector
, adding and removing whenstd::unique_ptr<T>
is borrowed from and returned to the pool. Easy to implement but feels wrong as I'm duplicating data. -
Use a
std::vector<std::reference_wrapper<std::unique_ptr<T>>>
. By keeping a reference to borrowedstd::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