42 lines
1.0 KiB
Markdown
42 lines
1.0 KiB
Markdown
|
|
# LinearAllocator::Allocate
|
|||
|
|
|
|||
|
|
```cpp
|
|||
|
|
void* Allocate(size_t size, size_t alignment = 8) override;
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
在缓冲区的当前位置顺序分配内存。每次分配都会将内部偏移量向前推进(对齐后)。如果剩余空间不足,则分配失败返回 `nullptr`。默认对齐值为 8 字节。
|
|||
|
|
|
|||
|
|
**参数:**
|
|||
|
|
- `size` - 请求的字节数
|
|||
|
|
- `alignment` - 内存对齐要求,默认为 8 字节
|
|||
|
|
|
|||
|
|
**返回:** 分配成功返回已对齐的指针,失败返回 `nullptr`
|
|||
|
|
|
|||
|
|
**复杂度:** O(1)
|
|||
|
|
|
|||
|
|
**示例:**
|
|||
|
|
|
|||
|
|
```cpp
|
|||
|
|
#include <XCEngine/Memory/LinearAllocator.h>
|
|||
|
|
|
|||
|
|
LinearAllocator allocator(1024);
|
|||
|
|
|
|||
|
|
// 分配 256 字节(8 字节对齐)
|
|||
|
|
void* ptr1 = allocator.Allocate(256);
|
|||
|
|
|
|||
|
|
// 分配 128 字节(16 字节对齐)
|
|||
|
|
void* ptr2 = allocator.Allocate(128, 16);
|
|||
|
|
|
|||
|
|
// 分配 64 字节(默认 8 字节对齐)
|
|||
|
|
void* ptr3 = allocator.Allocate(64);
|
|||
|
|
|
|||
|
|
// 检查是否成功
|
|||
|
|
if (!ptr1) {
|
|||
|
|
// 分配失败,缓冲区已满
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 相关文档
|
|||
|
|
|
|||
|
|
- [LinearAllocator 总览](linear-allocator.md) - 返回类总览
|