100 lines
2.5 KiB
Markdown
100 lines
2.5 KiB
Markdown
|
|
# MemoryManager
|
||
|
|
|
||
|
|
**命名空间**: `XCEngine::Memory`
|
||
|
|
|
||
|
|
**类型**: `class` (singleton)
|
||
|
|
|
||
|
|
**描述**: 全局内存管理器单例,提供系统分配器和各种专用分配器的创建。
|
||
|
|
|
||
|
|
## 概述
|
||
|
|
|
||
|
|
`MemoryManager` 是 XCEngine 内存管理系统的核心单例。它负责维护系统分配器,提供分配器工厂方法,并支持内存泄漏检测和报告。
|
||
|
|
|
||
|
|
## 单例访问
|
||
|
|
|
||
|
|
| 方法 | 描述 |
|
||
|
|
|------|------|
|
||
|
|
| `static MemoryManager& Get()` | 获取单例实例 |
|
||
|
|
|
||
|
|
## 公共方法
|
||
|
|
|
||
|
|
### 生命周期
|
||
|
|
|
||
|
|
| 方法 | 描述 |
|
||
|
|
|------|------|
|
||
|
|
| `void Initialize()` | 初始化内存管理器 |
|
||
|
|
| `void Shutdown()` | 关闭内存管理器 |
|
||
|
|
|
||
|
|
### 系统分配器
|
||
|
|
|
||
|
|
| 方法 | 描述 |
|
||
|
|
|------|------|
|
||
|
|
| `IAllocator* GetSystemAllocator()` | 获取系统默认分配器 |
|
||
|
|
|
||
|
|
### 分配器创建
|
||
|
|
|
||
|
|
| 方法 | 描述 |
|
||
|
|
|------|------|
|
||
|
|
| `std::unique_ptr<LinearAllocator> CreateLinearAllocator(size_t size)` | 创建线性分配器 |
|
||
|
|
| `std::unique_ptr<PoolAllocator> CreatePoolAllocator(size_t blockSize, size_t count)` | 创建内存池分配器 |
|
||
|
|
| `std::unique_ptr<ProxyAllocator> CreateProxyAllocator(const char* name)` | 创建代理分配器 |
|
||
|
|
|
||
|
|
### 内存管理
|
||
|
|
|
||
|
|
| 方法 | 描述 |
|
||
|
|
|------|------|
|
||
|
|
| `void SetTrackAllocations(bool track)` | 设置是否跟踪分配 |
|
||
|
|
| `void DumpMemoryLeaks()` | 输出内存泄漏报告 |
|
||
|
|
| `void GenerateMemoryReport()` | 生成内存使用报告 |
|
||
|
|
|
||
|
|
## 宏定义
|
||
|
|
|
||
|
|
### XE_ALLOC
|
||
|
|
|
||
|
|
```cpp
|
||
|
|
#define XE_ALLOC(allocator, size, ...) allocator->Allocate(size, ##__VA_ARGS__)
|
||
|
|
```
|
||
|
|
|
||
|
|
内存分配宏。
|
||
|
|
|
||
|
|
### XE_FREE
|
||
|
|
|
||
|
|
```cpp
|
||
|
|
#define XE_FREE(allocator, ptr) allocator->Free(ptr)
|
||
|
|
```
|
||
|
|
|
||
|
|
内存释放宏。
|
||
|
|
|
||
|
|
## 使用示例
|
||
|
|
|
||
|
|
```cpp
|
||
|
|
// 初始化
|
||
|
|
MemoryManager::Get().Initialize();
|
||
|
|
|
||
|
|
// 获取系统分配器
|
||
|
|
IAllocator* sysAlloc = MemoryManager::Get().GetSystemAllocator();
|
||
|
|
|
||
|
|
// 创建专用分配器
|
||
|
|
auto linearAlloc = MemoryManager::Get().CreateLinearAllocator(1024 * 1024);
|
||
|
|
auto poolAlloc = MemoryManager::Get().CreatePoolAllocator(sizeof(MyObject), 1000);
|
||
|
|
auto proxyAlloc = MemoryManager::Get().CreateProxyAllocator("GameFrame");
|
||
|
|
|
||
|
|
// 使用宏分配
|
||
|
|
void* ptr = XE_ALLOC(proxyAlloc, 256);
|
||
|
|
XE_FREE(proxyAlloc, ptr);
|
||
|
|
|
||
|
|
// 跟踪内存
|
||
|
|
MemoryManager::Get().SetTrackAllocations(true);
|
||
|
|
MemoryManager::Get().GenerateMemoryReport();
|
||
|
|
|
||
|
|
// 关闭
|
||
|
|
MemoryManager::Get().Shutdown();
|
||
|
|
```
|
||
|
|
|
||
|
|
## 相关文档
|
||
|
|
|
||
|
|
- [IAllocator](./memory-allocator.md) - 分配器接口
|
||
|
|
- [LinearAllocator](./memory-linear-allocator.md) - 线性分配器
|
||
|
|
- [PoolAllocator](./memory-pool-allocator.md) - 内存池分配器
|
||
|
|
- [ProxyAllocator](./memory-proxy-allocator.md) - 代理分配器
|