C++实现内存池
#include<iostream>
#include<list>
#include<cassert>
class MemoryPool {
private:
struct Block {
Block* next;
};
Block* freeList;
size_t blockSize;
size_t blockCount;
public:
MemoryPool(size_t size, size_t count) :
blockSize(size), blockCount(count), freeList(nullptr)
{
size_t poolSize = blockSize * blockCount;
freeList = (Block*)(std::malloc(poolSize));
Block* current = freeList;
for (size_t i = 0; i < blockCount - 1; ++i) {
current->next = reinterpret_cast<Block*>(reinterpret_cast<char*>(current));
current = current->next;
}
current->next = nullptr;
}
~MemoryPool() {
std::free(freeList);
}
void* allocate() {
if (!freeList) {
return nullptr;
}
Block* head = freeList;
freeList = head->next;
return head;
}
void deallocate(void* ptr) {
Block* block = static_cast<Block*>(ptr);
block->next = freeList;
freeList = block;
}
};
class smallInt {
public :
explicit operator int() const {
return val;
}
smallInt(int i=0):val(i) {
if (i < 0 || i>255) {
std::cout << "error"<<std::endl;
}
}
private:
size_t val;
};
int main() {
MemoryPool pool(128, 10);
void* p = pool.allocate();
std::cout << p << std::endl;
pool.deallocate(p);
std::cout << p << std::endl;
return 0;
}