swa*_*log 18 c++ pool smart-pointers c++11
我正在玩c ++ - 想法,并且对这个问题有点困惑.
我想要一个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())
Run Code Online (Sandbox Code Playgroud)
基本实现,除了重要的最终测试外,将通过测试:
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_;
};
Run Code Online (Sandbox Code Playgroud)
问题:如何进行以便acquire()
返回一个unique_ptr
类型,使得删除器知道this
并调用this->add(...)
将资源返回池中.
swa*_*log 18
该实现使用unique_ptr
自定义删除器将对象返回到池中.这两个acquire
和release
的O(1)
.此外,unique_ptr
自定义删除器可以隐式转换为shared_ptr
.
template <class T>
class SharedPool
{
public:
using ptr_type = std::unique_ptr<T, std::function<void(T*)> >;
SharedPool() {}
virtual ~SharedPool(){}
void add(std::unique_ptr<T> t) {
pool_.push(std::move(t));
}
ptr_type acquire() {
assert(!pool_.empty());
ptr_type tmp(pool_.top().release(),
[this](T* ptr) {
this->add(std::unique_ptr<T>(ptr));
});
pool_.pop();
return std::move(tmp);
}
bool empty() const {
return pool_.empty();
}
size_t size() const {
return pool_.size();
}
private:
std::stack<std::unique_ptr<T> > pool_;
};
Run Code Online (Sandbox Code Playgroud)
用法示例:
SharedPool<int> pool;
pool.add(std::unique_ptr<int>(new int(42)));
pool.add(std::unique_ptr<int>(new int(84)));
pool.add(std::unique_ptr<int>(new int(1024)));
pool.add(std::unique_ptr<int>(new int(1337)));
// Three ways to express the unique_ptr object
auto v1 = pool.acquire();
SharedPool<int>::ptr_type v2 = pool.acquire();
std::unique_ptr<int, std::function<void(int*)> > v3 = pool.acquire();
// Implicitly converted shared_ptr with correct deleter
std::shared_ptr<int> v4 = pool.acquire();
// Note that adding an acquired object is (correctly) disallowed:
// pool.add(v1); // compiler error
Run Code Online (Sandbox Code Playgroud)
您可能已经遇到了此实现的严重问题.以下用法并非不可想象:
std::unique_ptr< SharedPool<Widget> > pool( new SharedPool<Widget> );
pool->add(std::unique_ptr<Widget>(new Widget(42)));
pool->add(std::unique_ptr<Widget>(new Widget(84)));
// [Widget,42] acquired(), and released from pool
auto v1 = pool->acquire();
// [Widget,84] is destroyed properly, together with pool
pool.reset(nullptr);
// [Widget,42] is not destroyed, pool no longer exists.
v1.reset(nullptr);
// Memory leak
Run Code Online (Sandbox Code Playgroud)
我们需要一种方法来保存删除器所需的活动信息以进行区分
这样做的一种方式(通过TC所建议的),在具有每个删除器保持weak_ptr
到shared_ptr
构件SharedPool
.这使得删除器知道池是否已被销毁.
template <class T>
class SharedPool
{
private:
struct External_Deleter {
explicit External_Deleter(std::weak_ptr<SharedPool<T>* > pool)
: pool_(pool) {}
void operator()(T* ptr) {
if (auto pool_ptr = pool_.lock()) {
try {
(*pool_ptr.get())->add(std::unique_ptr<T>{ptr});
return;
} catch(...) {}
}
std::default_delete<T>{}(ptr);
}
private:
std::weak_ptr<SharedPool<T>* > pool_;
};
public:
using ptr_type = std::unique_ptr<T, External_Deleter >;
SharedPool() : this_ptr_(new SharedPool<T>*(this)) {}
virtual ~SharedPool(){}
void add(std::unique_ptr<T> t) {
pool_.push(std::move(t));
}
ptr_type acquire() {
assert(!pool_.empty());
ptr_type tmp(pool_.top().release(),
External_Deleter{std::weak_ptr<SharedPool<T>*>{this_ptr_}});
pool_.pop();
return std::move(tmp);
}
bool empty() const {
return pool_.empty();
}
size_t size() const {
return pool_.size();
}
private:
std::shared_ptr<SharedPool<T>* > this_ptr_;
std::stack<std::unique_ptr<T> > pool_;
};
Run Code Online (Sandbox Code Playgroud)
这是一个自定义删除程序,用于检查池是否仍处于活动状态.
template<typename T>
class return_to_pool
{
std::weak_ptr<SharedPool<T>> pool
public:
return_to_pool(const shared_ptr<SharedPool<T>>& sp) : pool(sp) { }
void operator()(T* p) const
{
if (auto sp = pool.lock())
{
try {
sp->add(std::unique_ptr<T>(p));
return;
} catch (const std::bad_alloc&) {
}
}
std::default_delete<T>{}(p);
}
};
template <class T>
class SharedPool : std::enable_shared_from_this<SharedPool<T>>
{
public:
using ptr_type = std::unique_ptr<T, return_to_pool<T>>;
...
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<SharedPool<int>>();
Run Code Online (Sandbox Code Playgroud)
虽然这个问题很老并且已经得到了回答,但我对@swalog 提出的解决方案有一个小小的评论。
由于双重删除,Deleter 函子可能会导致内存损坏:
void operator()(T* ptr) {
if (auto pool_ptr = pool_.lock()) {
try {
(*pool_ptr.get())->add(std::unique_ptr<T>{ptr});
return;
} catch(...) {}
}
std::default_delete<T>{}(ptr);
}
Run Code Online (Sandbox Code Playgroud)
unique_ptr
当异常被捕获时,这里创建的将被销毁。因此,
std::default_delete<T>{}(ptr);
Run Code Online (Sandbox Code Playgroud)
将导致双重删除。
它可以通过更改从 T* 创建 unique_ptr 的位置来修复:
void operator()(T* ptr) {
std::unique_ptr<T> uptr(ptr);
if (auto pool_ptr = pool_.lock()) {
try {
(*pool_ptr.get())->add(std::move(uptr));
return;
} catch(...) {}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10853 次 |
最近记录: |