67 lines
2.1 KiB
Markdown
67 lines
2.1 KiB
Markdown
|
|
# LinearAllocator
|
|||
|
|
|
|||
|
|
**命名空间**: `XCEngine::Memory`
|
|||
|
|
|
|||
|
|
**类型**: `class`
|
|||
|
|
|
|||
|
|
**描述**: 线性分配器,适合帧分配和临时对象。
|
|||
|
|
|
|||
|
|
## 概述
|
|||
|
|
|
|||
|
|
`LinearAllocator` 是一种顺序分配器,预分配一个大缓冲区,每次分配从缓冲区起始位置顺序分配,偏移量递增。它不适合需要释放任意块的场景,但分配和清除非常高效,常用于帧分配器。
|
|||
|
|
|
|||
|
|
## 公共方法
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `LinearAllocator` | 构造线性分配器 |
|
|||
|
|
| `~LinearAllocator` | 析构函数,释放底层缓冲区 |
|
|||
|
|
| `Allocate` | 顺序分配内存 |
|
|||
|
|
| `Free` | 无效果(不支持) |
|
|||
|
|
| `Reallocate` | 不支持(始终返回 nullptr) |
|
|||
|
|
| `Clear` | 清空所有分配 |
|
|||
|
|
| `GetMarker` | 获取当前位置标记 |
|
|||
|
|
| `SetMarker` | 回滚到指定标记位置 |
|
|||
|
|
| `GetUsedSize` | 获取已使用字节数 |
|
|||
|
|
| `GetCapacity` | 获取总容量 |
|
|||
|
|
|
|||
|
|
## 构造函数
|
|||
|
|
|
|||
|
|
```cpp
|
|||
|
|
explicit LinearAllocator(size_t size, IAllocator* parent = nullptr);
|
|||
|
|
~LinearAllocator() override;
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
构造一个线性分配器,预分配指定大小的缓冲区。如果提供了 `parent` 分配器,则使用它分配底层缓冲区;否则使用系统默认分配(`_aligned_malloc`,8 字节对齐)。
|
|||
|
|
|
|||
|
|
**参数:**
|
|||
|
|
- `size` - 预分配的缓冲区大小(字节数)
|
|||
|
|
- `parent` - 父分配器,用于分配底层缓冲区,默认为 `nullptr`(使用系统分配)
|
|||
|
|
|
|||
|
|
**返回:** 无
|
|||
|
|
|
|||
|
|
**复杂度:** O(n),需要分配 `size` 大小的缓冲区
|
|||
|
|
|
|||
|
|
**注意:** `Free` 和 `Reallocate` 方法无实际效果。`Free` 是空操作,`Reallocate` 始终返回 `nullptr`。
|
|||
|
|
|
|||
|
|
**示例:**
|
|||
|
|
|
|||
|
|
```cpp
|
|||
|
|
#include <XCEngine/Memory/LinearAllocator.h>
|
|||
|
|
|
|||
|
|
// 使用系统分配器创建 1MB 线性分配器
|
|||
|
|
LinearAllocator allocator1(1024 * 1024);
|
|||
|
|
|
|||
|
|
// 使用指定的父分配器
|
|||
|
|
IAllocator* parent = MemoryManager::Get().GetSystemAllocator();
|
|||
|
|
LinearAllocator allocator2(1024 * 1024, parent);
|
|||
|
|
|
|||
|
|
// 默认 8 字节对齐
|
|||
|
|
void* ptr = allocator1.Allocate(256);
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 相关文档
|
|||
|
|
|
|||
|
|
- [Memory 模块总览](../memory.md) - 返回模块总览
|
|||
|
|
- [IAllocator](../allocator/allocator.md) - 分配器接口
|