13.1 对齐内存分配器
渲染引擎大量使用 SIMD 处理顶点/矩阵数据,而 SIMD 指令(如 _mm_load_ps)要求数据地址按 16 字节对齐。普通 new/malloc 只保证 max_align_t 对齐,不保证更高对齐——所以 OGRE 自己写了一套对齐分配器。
本章与站内既有内容的分工
helio 从零实现讲「如何搭内存池」;本节讲 OGRE 里最简单也最经典的一招:多分配一点,存偏移量。容器策略在 13.3。
AlignedMemory:allocate 的偏移头技巧
OgreAlignedAllocator.h 声明 AlignedMemory 类,注释说明用途是 SIMD/缓存友好:
// OgreMain/include/OgreAlignedAllocator.h:class AlignedMemory(v14.6.3 源码摘录,已删减)
class _OgreExport AlignedMemory
{
public:
/** Allocate memory with given alignment.
@param
size The size of memory need to allocate.
@param
alignment The alignment of result pointer, must be power of two
and in range [1, 128].
*/
static DECL_MALLOC void* allocate(size_t size, size_t alignment);
/** Allocate memory with default platform dependent alignment.
*/
static DECL_MALLOC void* allocate(size_t size);
/** Deallocate memory that allocated by this class.
@param
p Pointer to the memory allocated by this class or <b>NULL</b> pointer.
*/
static void deallocate(void* p);
};
实现是经典的对齐分配技巧:
// OgreMain/src/OgreAlignedAllocator.cpp:AlignedMemory::allocate/deallocate(v14.6.3 教学示意,参照上游同名实现,已删减)
void* AlignedMemory::allocate(size_t size, size_t alignment)
{
assert(0 < alignment && alignment <= 128 && Bitwise::isPO2(alignment));
unsigned char* p = new unsigned char[size + alignment];
size_t offset = alignment - (size_t(p) & (alignment-1));
unsigned char* result = p + offset;
result[-1] = (unsigned char)offset;
return result;
}
//---------------------------------------------------------------------
void* AlignedMemory::allocate(size_t size)
{
return allocate(size, OGRE_SIMD_ALIGNMENT);
}
//---------------------------------------------------------------------
void AlignedMemory::deallocate(void* p)
{
if (p)
{
unsigned char* mem = (unsigned char*)p;
mem = mem - mem[-1];
delete [] mem;
}
}
原理拆解:
- 多分配
alignment字节:new unsigned char[size + alignment],原始块起点p无法保证对齐; - 算偏移:
offset = alignment - (p & (alignment-1))——把p补到下一个对齐边界所需的字节数; - 返回对齐指针:
result = p + offset,地址是alignment的倍数; - 存偏移:
result[-1] = offset——对齐指针前一字节记着「原指针在哪」; - 释放:
mem = p - p[-1],从对齐指针减回偏移量找回原指针,delete[]之。
0 p result p+size+alignment
| |<--- offset -->|
| 原始块 |...................对齐指针...........
result[-1] = offset (p - p[-1] 即可还原)
result[-1] 能用是因为 offset 至少为 1、至多为 alignment(≤128),一个 unsigned char 存得下。Bitwise::isPO2(alignment) 断言对齐值必须是 2 的幂。
AlignedAllocator:STL 兼容包装
头文件里还有一个 STL 兼容的分配器,把 AlignedMemory 接进标准容器:
// OgreMain/include/OgreAlignedAllocator.h:AlignedAllocator(v14.6.3 源码摘录,已删减)
/// STL compatible wrapper for @ref AlignedMemory
template<typename T, size_t Alignment>
struct AlignedAllocator : public std::allocator<T>
{
AlignedAllocator() : std::allocator<T>() {}
template <class U>
AlignedAllocator(const AlignedAllocator<U, Alignment>& other) {};
template<class Other>
struct rebind { using other = AlignedAllocator<Other, Alignment>; };
T* allocate(size_t n) {
return static_cast<T*>(AlignedMemory::allocate(n * sizeof(T), Alignment));
}
T* allocate(size_t n, const void* hint) { // deprecated in C++17
return static_cast<T*>(AlignedMemory::allocate(n * sizeof(T), Alignment));
}
void deallocate(T* p, size_t /*n*/) {
AlignedMemory::deallocate(p);
}
};
它继承 std::allocator<T>、实现 allocate/deallocate/rebind,就能用于 std::vector<T, AlignedAllocator<T, 16>>——容器整体按 16 字节对齐存放元素,便于整块 SIMD 加载。注释提醒:这是给高级用户的,OGRE 内部会按需自动选对齐策略。
源码定位
OgreMain/include/OgreAlignedAllocator.h:class AlignedMemory、template AlignedAllocator<T, Alignment>OgreMain/src/OgreAlignedAllocator.cpp:AlignedMemory::allocate(偏移头技巧)、deallocate(p - p[-1]还原)
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面复现对齐分配的偏移头技巧。它与 src/13-1-aligned-memory.cpp 逐字节一致:
// file: src/13-1-aligned-memory.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/13-1-aligned-memory.cpp -o bin/13-1-aligned-memory && ./bin/13-1-aligned-memory
//
// 复现 AlignedMemory::allocate / deallocate 的对齐分配技巧:
// new/malloc 多分配 alignment 字节,把指针补齐到对齐边界;
// 偏移量存进 result[-1];deallocate 时用 result[-1] 找回原指针。
// (对应 OgreAlignedAllocator.cpp 的实现)
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cstddef>
#include <cstdlib>
namespace ogre_repro {
// 对应 Ogre::AlignedMemory(用 malloc 简化 new[])
class AlignedMemory {
public:
// 对应 AlignedMemory::allocate(size, alignment):alignment 必须为 2 的幂且 ≤128
static void* allocate(size_t size, size_t alignment) {
if (size == 0) return nullptr;
unsigned char* p = static_cast<unsigned char*>(std::malloc(size + alignment));
size_t offset = alignment - (reinterpret_cast<size_t>(p) & (alignment - 1));
unsigned char* result = p + offset;
result[-1] = static_cast<unsigned char>(offset); // 原偏移存进前一个字节
return result;
}
// 对应 AlignedMemory::deallocate:p - p[-1] 找回原指针后释放
static void deallocate(void* p) {
if (p) {
unsigned char* mem = static_cast<unsigned char*>(p);
mem = mem - mem[-1];
std::free(mem);
}
}
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
// 对齐到 16 字节:反复分配释放
for (int i = 0; i < 100; ++i) {
void* p = AlignedMemory::allocate(37, 16);
CHECK((reinterpret_cast<size_t>(p) & 15) == 0); // 地址是 16 的倍数
// 分配区可读写
auto* bytes = static_cast<unsigned char*>(p);
bytes[0] = 0xAB;
bytes[36] = 0xCD;
CHECK(bytes[36] == 0xCD);
AlignedMemory::deallocate(p);
}
// 对齐到 32 / 64
for (size_t a : {size_t{32}, size_t{64}}) {
void* p = AlignedMemory::allocate(100, a);
CHECK((reinterpret_cast<size_t>(p) & (a - 1)) == 0);
AlignedMemory::deallocate(p);
}
// null 指针释放安全
AlignedMemory::deallocate(nullptr);
return lab::report("13-1 内存与容器:对齐内存分配器");
}
本机实测(Apple clang 16,clang++ -std=c++20):编译通过(-Wall 零警告),断言 202/202 通过。
小结
AlignedMemory::allocate(size, alignment):多分配alignment字节,偏移量存result[-1]。deallocate用p - p[-1]还原原指针,NULL安全。- 对齐值要求是 2 的幂且 ≤128(
Bitwise::isPO2断言)。 AlignedAllocator<T, Alignment>是 STL 兼容包装,接进std::vector即得到对齐容器。
阅读导航:上一节:12.3 渲染循环中的事件时序 · 下一节:13.2 SharedPtr 智能指针 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。