Files
XCEngine/docs/api/memory/memory-linear-allocator.md

83 lines
2.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# LinearAllocator
**命名空间**: `XCEngine::Memory`
**类型**: `class`
**描述**: 线性分配器,提供顺序分配和一次性释放的内存管理,适用于帧分配和临时对象。
## 概述
`LinearAllocator` 以顺序方式分配内存,每次分配都紧接在上一次分配之后。它不支持单个内存块的释放,只能通过 `Clear()` 一次性清空所有内存。这使得它非常适合作为帧分配器,每帧开始时 Clear 即可。
## 公共方法
### 构造/析构
| 方法 | 描述 |
|------|------|
| `explicit LinearAllocator(size_t size, IAllocator* parent = nullptr)` | 构造函数,预分配指定大小的缓冲区 |
| `~LinearAllocator()` | 析构函数,释放所有内存 |
### IAllocator 实现
| 方法 | 描述 |
|------|------|
| `void* Allocate(size_t size, size_t alignment = 8) override` | 顺序分配内存 |
| `void Free(void* ptr) override` | 空操作(不支持单个释放) |
| `void* Reallocate(void* ptr, size_t newSize) override` | 重新分配(总是分配新内存) |
### 线性操作
| 方法 | 描述 |
|------|------|
| `void Clear()` | 清空所有分配,下一次分配从头开始 |
| `void* GetMarker() const` | 获取当前分配位置标记 |
| `void SetMarker(void* marker)` | 恢复到指定标记位置 |
### 状态查询
| 方法 | 描述 |
|------|------|
| `size_t GetUsedSize() const` | 获取已使用的字节数 |
| `size_t GetCapacity() const` | 获取总容量 |
### 统计
| 方法 | 描述 |
|------|------|
| `size_t GetTotalAllocated() const` | 返回已使用字节数 |
| `size_t GetTotalFreed() const` | 返回 0 |
| `size_t GetPeakAllocated() const` | 返回容量大小 |
| `size_t GetAllocationCount() const` | 返回 0 |
## 使用示例
```cpp
// 创建 1MB 的线性分配器
auto allocator = std::make_unique<LinearAllocator>(1024 * 1024);
// 分配临时内存
void* ptr1 = allocator->Allocate(256);
void* ptr2 = allocator->Allocate(512);
void* ptr3 = allocator->Allocate(128);
// 保存标记
void* marker = allocator->GetMarker();
// 分配一些临时内存
void* temp = allocator->Allocate(64);
// 恢复到标记位置(释放 temp
allocator->SetMarker(marker);
// 每帧结束时清空
allocator->Clear();
```
## 相关文档
- [IAllocator](./memory-allocator.md) - 分配器接口
- [PoolAllocator](./memory-pool-allocator.md) - 内存池分配器
- [ProxyAllocator](./memory-proxy-allocator.md) - 代理分配器