Can someone please advise on how to return the unique pointer from a templatised unique pointer pool with a custom deletor.
In the code snippet below i am using ObjectPool.h as my template class to get a stack of unique pointers . I am using ObjectPool to create a sharedpool object in DBConnection.h and later in DBConnection.cpp i am simply returning the object to DBExec .
I get compile errors in DBConnection.cpp related to conversion of pointer with deleter to normal unique pointer.
> 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 >;
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 */
Aucun commentaire:
Enregistrer un commentaire