-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_pool_ctr.cpp
More file actions
58 lines (51 loc) · 1.67 KB
/
memory_pool_ctr.cpp
File metadata and controls
58 lines (51 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//
// Created by wnc on 2025/9/15.
//
#include "memory_pool_ctr.h"
#include <limits>
#include <iostream>
#include <algorithm>
#include <stdexcept>
MemoryPoolCtr::MemoryPoolCtr(const std::initializer_list<MemPoolParam>& params) {
for (auto& p : params) {
pools_.emplace_back(p.block_size, p.block_count);
}
// 按 block_size 升序排列,方便选择
std::sort(pools_.begin(), pools_.end(),
[](const MemoryPool& a, const MemoryPool& b) {
return a.getBlockSize() < b.getBlockSize();
});
}
// 根据请求大小选择最小可用块
MemoryPool& MemoryPoolCtr::getPoolForSize(size_t size) {
size_t best_fit = std::numeric_limits<size_t>::max();
size_t index = 0;
bool found = false;
for (size_t i = 0; i < pools_.size(); ++i) {
size_t bsize = pools_[i].getBlockSize();
if (bsize >= size && bsize < best_fit) {
best_fit = bsize;
index = i;
found = true;
}
}
if (!found) {
throw std::runtime_error("没有找到合适的子内存池");
}
return pools_[index];
}
void MemoryPoolCtr::reportLeaks() const {
for (size_t i = 0; i < pools_.size(); ++i) {
std::cout << "子内存池 " << i << " (block_size = " << pools_[i].getBlockSize()
<< ", pool_capacity = " << pools_[i].getPoolCapacity()
<< ") 泄漏报告:" << std::endl;
pools_[i].reportLeaks();
}
}
// 在所有子池中查找哪个池管理该 ptr(通过 MemoryPool::owns)
MemoryPool* MemoryPoolCtr::findPoolForPtr(void* ptr) noexcept {
for (auto &pool : pools_) {
if (pool.owns(ptr)) return &pool;
}
return nullptr;
}