std::allocator 的简单用法

来源:互联网 发布:windows 评估副本 编辑:程序博客网 时间:2024/06/05 15:15
#include <memory>//shared_ptr && allocator/* *@brief *Xxx内存池 *@multi-thread-safe:NO */class XxxMemoryPool{friend class XxxMgr;typedef std::shared_ptr<Xxx> XxxPtr;typedef std::allocator<char> XxxPool;typedef std::shared_ptr<XxxPool> PoolPtr;public:~XxxMemoryPool();private:XxxMemoryPool() = default;void Init();XxxPtr GetXxx();void Free(Xxx* ptr);private:PoolPtr _Xxx_pool;const static int Xxx_SIZE = sizeof(Xxx);};//////////////////////////////////////////////////////////////////////////XxxMemoryPool::~XxxMemoryPool(){}void Xxx_client::XxxMemoryPool::Init(){if (_Xxx_pool){_Xxx_pool.reset();_Xxx_pool = nullptr; }_Xxx_pool = PoolPtr(new XxxPool());if (!_Xxx_pool){const char *err_msg = "new a memory pool failed.";LOG4CPLUS_ERROR(Logger::getRoot(), err_msg);throw err_msg;}}XxxMemoryPool::XxxPtr XxxMemoryPool::GetXxx(){if (!_Xxx_pool){LOG4CPLUS_ERROR(Logger::getRoot(), "the memory pool ptr is nullptr. don't allocate memory.");return nullptr;}void* buff = _Xxx_pool->allocate(Xxx_SIZE);if (buff){Xxx* Xxx = new(buff)Xxx;XxxPtr Xxx_ptr(Xxx, std::bind(&XxxMemoryPool::Free, this, std::placeholders::_1));return Xxx_ptr;}else{LOG4CPLUS_ERROR(Logger::getRoot(), "allocate memory failed.");return nullptr;}}void Xxx_client::XxxMemoryPool::Free(Xxx* ptr){if (ptr){ptr->~Xxx();char* p = (char*)(ptr);_Xxx_pool->deallocate(p, Xxx_SIZE);}else{LOG4CPLUS_ERROR(Logger::getRoot(), "don't free memory because ptr passed in is nullptr.");}}

0 0
原创粉丝点击