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 requested (through acquire()), it returns the object as a unique_ptr that, upon deletion, causes the resource to be returned to the pool.
The unit tests would be:
// Create the pool, that holds (for simplicity, int objects)
SharedPool<int> pool;
TS_ASSERT(pool.empty());
// Add an object to the pool, which is now, no longer empty
pool.add(std::unique_ptr<int>(new int(42)));
TS_ASSERT(!pool.empty());
// Pop this object within its own scope, causing the pool to be empty
{
std::unique_ptr<int> v = pool.acquire();
TS_ASSERT_EQUALS(*v, 42);
TS_ASSERT(pool.empty());
}
// Object should now have returned to the pool
TS_ASSERT(!pool.empty())
Basic implementation, which would pass the tests, except for the important final test:
template <class T>
class SharedPool
{
public:
SharedPool(){}
virtual ~SharedPool(){}
void add(std::unique_ptr<T> t) {
pool_.push(std::move(t));
}
std::unique_ptr<T> acquire() {
assert(!pool_.empty());
std::unique_ptr<T> tmp(std::move(pool_.top()));
pool_.pop();
return std::move(tmp);
}
bool empty() const {
return pool_.empty();
}
private:
std::stack<std::unique_ptr<T> > pool_;
};
The question: How to go about so that acquire() returns a unique_ptr of a type such that the deleter has knowledge of this, and calls this->add(...), returning the resource back to the pool.
Aucun commentaire:
Enregistrer un commentaire