I'm implementing a object pool with shared_ptr to access with multiple thread. Any suggestions to improve my implementation
template <typename T>
class Section : public std::enable_shared_from_this<Section<T>>
{
public:
template <typename... E>
Section(std::size_t size, E... args)
: std::enable_shared_from_this<Section<T>>()
, m_mem(size,T(args...))
{
for(auto& itr: m_mem)
{
destroy(&itr);
m_objs.push(&itr);
}
}
virtual ~Section() = default;
void isEmpty() const
{
std::unique_lock<std::mutex> lk(m_lock);
return m_objs.empty();
}
template <typename... E>
std::shared_ptr<T> create(E... args)
{
T* obj = getObject();
if(obj != nullptr)
{
new (obj) T(args...);
}
return std::shared_ptr<T>(obj,[this](T* ptr)->void
{
destroy(ptr);
std::unique_lock<std::mutex> lk(m_lock);
m_objs.push(ptr);
});
}
private:
std::list<T> m_mem;
std::queue<T*> m_objs;
mutable std::mutex m_lock;
T* getObject()
{
std::unique_lock<std::mutex> lk(m_lock);
if (!m_objs.empty())
{
T* obj = m_objs.front();
m_objs.pop();
return obj;
}
return nullptr;
}
void destroy(T* obj)
{
obj->~T();
}
};