c++ 11 简约版内存池实现
使用c++11的智能指针实现一个简约版的内存池
.h文件
//
// Created by 李文龙 on 2019/12/1.
//
#ifndef THREAD_TOOL_TEST_MEMORY_POOL_H
#define THREAD_TOOL_TEST_MEMORY_POOL_H
#include "common.h"
#include <list>
#include <map>
#include <mutex>
#include <memory>
#include <string>
NS_ILONG_BEGIN
template <class T>
class MemoryPool{
public:
constexpr static int kMaxBufferCount = 30;
MemoryPool(int maxCount = kMaxBufferCount, const std::string &tag = "");
virtual ~MemoryPool();
std::shared_ptr<T> getObject();
void clearAllObjects();
int getFreeCount();
int getUsedCount();
private:
std::list<std::shared_ptr<T>> buffers_;
std::mutex mutex_;
int max_buffer_count_;
std::string tag_;
};
NS_ILONG_END
#endif //THREAD_TOOL_TEST_MEMORY_POOL_H
.cpp文件
//
// Created by 李文龙 on 2019/12/1.
//
#include "memory_pool.h"
NS_ILONG_BEGIN
template <class T>
MemoryPool<T>::MemoryPool(int maxCount, const std::string &tag)
:max_buffer_count_{maxCount},
tag_{tag}{
buffers_.clear();
}
template <class T>
MemoryPool<T>::~MemoryPool() {
clearAllObjects();
}
template <class T>
std::shared_ptr<T> MemoryPool<T>::getObject(){
std::lock_guard<std::mutex> guard(mutex_);
int used_count = buffers_.size();
if(used_count > max_buffer_count_){
std::shared_ptr<T> data;
return data;
}
for (const std::shared_ptr<T> &buffer : buffers_) {
if (buffer.use_count() == 1){
return buffer;
}
}
std::shared_ptr<T> data = std::make_shared<T>();
buffers_.push_back(data);
return data;
}
template <class T>
void MemoryPool<T>::clearAllObjects(){
std::lock_guard<std::mutex> guard(mutex_);
buffers_.clear();
}
template <class T>
int MemoryPool<T>::getFreeCount(){
std::lock_guard<std::mutex> guard(mutex_);
int freeCount = 0;
for (const std::shared_ptr<T> &buffer : buffers_) {
if (buffer.use_count() == 1){
freeCount++;
}
}
return freeCount;
}
template <class T>
int MemoryPool<T>::getUsedCount(){
std::lock_guard<std::mutex> guard(mutex_);
int usedCount = 0;
for (const std::shared_ptr<T> &buffer : buffers_) {
if (buffer.use_count() > 1){
usedCount++;
}
}
return usedCount;
}
NS_ILONG_END
测试程序
#include "memory_pool.cpp"
class DataBuffer{
public:
DataBuffer(){
}
};
int main() {
MemoryPool<DataBuffer> memoryPool;
for(int i = 0; i < 10; i++){
auto data = memoryPool.GetObject();
}
int count = memoryPool.GetFreeCount();
ELOG_DEBUG("Memory Pool Count: %d", count);
auto data = memoryPool.GetObject();
count = memoryPool.GetFreeCount();
ELOG_DEBUG("Memory Pool Count: %d", count);
memory_pool_.ClearAllObjects();
count = memoryPool.GetFreeCount();
ELOG_DEBUG("Memory Pool Count: %d", count);
}