gpt4 book ai didi

c++ - 从 unique_ptr 拉出 unique_ptr

转载 作者:行者123 更新时间:2023-11-28 01:49:09 25 4
gpt4 key购买 nike

有人可以建议如何使用自定义删除器从模板化唯一指针池返回唯一指针。

在下面的代码片段中,我使用 ObjectPool.h 作为我的模板类来获取一堆唯一指针。我正在使用 ObjectPool 在 DBConnection.h 中创建一个共享池对象,后来在 DBConnection.cpp 中我只是将该对象返回给 DBExec 。

我在 DBConnection.cpp 中遇到与将带删除器的指针转换为普通唯一指针相关的编译错误。

> Class that will manage connection objects. 
**DBConnectionPool.h**
#ifndef DBCONNECTIONPOOL_H
#define DBCONNECTIONPOOL_H
#include "DBExec.h"
#include "ObjectPool.h"
class DBConnectionPool {
static SharedPool<DBExec> pool;
static DBConnectionPool* instance;
DBConnectionPool& operator=(const DBConnectionPool&);
DBConnectionPool(const DBConnectionPool&);;
DBConnectionPool(){};
public:
...
**static std::unique_ptr<DBExec> getQueryObject();**
};



#endif /* DBCONNECTIONPOOL_H */

**DBConnection.cpp**
>implementation of getQueryObject
**std::unique_ptr<DBExec> DBConnectionPool::getQueryObject() {
return std::move(pool.acquire());
}**

/* Class that manages the unique pointer */
**ObjectPool.h**
#ifndef OBJECTPOOL_H
#define OBJECTPOOL_H
#include <memory>
#include <stack>
#include <mutex>
#include <assert.h>
template <class T>
class SharedPool {

/* Class that manages the unique pointer */
public:
using ptr_type = std::unique_ptr<T, std::function<void(T*)> >;

SharedPool() {
}

virtual ~SharedPool() {
}

void add(std::unique_ptr<T> t) {
std::lock_guard<std::mutex> lck (mt);
pool_.push(std::move(t));
}

ptr_type acquire() {
std::lock_guard<std::mutex> lck (mt);
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 {
std::lock_guard<std::mutex> lck (mt);
return pool_.empty();
}

size_t size() const {
std::lock_guard<std::mutex> lck (mt);
return pool_.size();
}
std::stack<std::unique_ptr<T>>& getPoolStack () {
return pool_;
}
private:
> thread safe
std::mutex mt;
std::stack<std::unique_ptr<T> > pool_;
};

#endif /* OBJECTPOOL_H */

最佳答案

std::unique_ptr<T,D>std::unique_ptr<T>是不相关的类型(除非 D=std::default_delete<T> )。因此,您需要在所有 typedef 中指定删除器的类型。

下一个问题是您实际上无法输入删除器的类型,因为它是 lambda 类型。因此,您可能必须从 lambda 转换为命名的可调用类型。

template <class T>
class SharedPool {
public:
class Deleter {
public:
void operator()(T* ptr) const {
pool->add(std::unique_ptr<T,Deleter>(ptr));
}
private:
explicit Deleter(SharedPool* pool) : pool(pool) {}
SharedPool* pool;
friend class SharedPool<T>;
};
using ptr_type = std::unique_ptr<T, Deleter>;

您也可以考虑使用 std::shared_ptr因为它类型删除其删除器类型,但您似乎不需要共享。

关于c++ - 从 unique_ptr<T,Deleter> 拉出 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com