【发布时间】:2015-03-05 20:20:15
【问题描述】:
我对 c++-ideas 很感兴趣,但遇到了这个问题。
我想要一个管理资源池的LIFO 类。
当请求资源时(通过acquire()),它会以unique_ptr 的形式返回对象,删除后会导致资源返回到池中。
单元测试是:
// 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
{
auto v = pool.acquire();
TS_ASSERT_EQUALS(*v, 42);
TS_ASSERT(pool.empty());
}
// Object should now have returned to the pool
TS_ASSERT(!pool.empty())
基本实现,将通过测试,除了重要的最终测试:
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_;
};
问题:如何进行以使acquire()返回一个unique_ptr,其类型使得删除器知道this,并调用this->add(...),返回资源回到游泳池。
【问题讨论】:
-
如果您使用自定义删除器,则不再返回
std::unique_ptr<T>。要么修复签名,要么使用带有类型擦除删除器的东西(例如shared_ptr)。 -
我知道 :),它可能是
std::unique_ptr<T, std::function<void(T*)> >类型,但我不想添加半答案。我的困惑更多是如何将其与std::bind正确结合。我将依靠更有经验的 C++ 开发人员来填补空白。之后我想解决的另一种方法是返回一个std::shared_ptr,但是,如果它正确地解决了std::unique_ptr,它会自动解决shared_ptr的情况。
标签: c++ c++11 smart-pointers pool