I\'m having fun with c++-ideas, and got a little stuck with this problem.
I would like a LIFO
class that manages a pool of resources.
When a resource is
Here's a custom deleter that checks if the pool is still alive.
template
class return_to_pool
{
std::weak_ptr> pool
public:
return_to_pool(const shared_ptr>& sp) : pool(sp) { }
void operator()(T* p) const
{
if (auto sp = pool.lock())
{
try {
sp->add(std::unique_ptr(p));
return;
} catch (const std::bad_alloc&) {
}
}
std::default_delete{}(p);
}
};
template
class SharedPool : std::enable_shared_from_this>
{
public:
using ptr_type = std::unique_ptr>;
...
ptr_type acquire()
{
if (pool_.empty())
throw std::logic_error("pool closed");
ptr_type tmp{pool_.top().release(), this->shared_from_this()};
pool_.pop();
return tmp;
}
...
};
// SharedPool must be owned by a shared_ptr for enable_shared_from_this to work
auto pool = std::make_shared>();