如何在字节存储中获取对齐指针并预估异构对象存储需求?
可移植的异构对象存储对齐与空间预估方案
存储场景
我有两种形式的字节数组存储:
- 栈上存储(无对齐要求):
// storage on the stack, no requirement on alignment unsigned char storage[N];
- 堆上存储(无对齐要求):
// storage on the heap, no requirement on alignment unsigned char *storage = new unsigned char[N*sizeof(T)];
参照monotonic_resource_buffer的设计思路,某一时刻我持有存储内某字节的有效指针p,希望找到下一个适合放置T类型对象的对齐地址(缓冲区中p之后无其他存活对象)。
使用std::align的尝试与问题
我尝试用std::align实现,但存在几个问题:
// let p a pointer to a byte inside storage, originally set to storage // issue storage+N-p is std::ptrdiff_t not std::size_t // remaining storage should probably be kept up to date manually into a dedicated variable // properly aligned storage to hold M contiguous T objects or nullptr std::align(alignas(T),M,p,storage+N-p); // or (using a dedicated variable) std::align(alignas(T),M,p,remaining_space); // major issue, the required remaining_space cannot be known in advance AFAIU, // it may lead to expansive reallocation(s) and copy(ies)
(注:上述代码存在笔误,应使用alignof而非alignas,为不影响讨论保留原样)
问题点:
storage+N-p的类型是std::ptrdiff_t,但std::align要求剩余空间参数为std::size_t,类型不匹配;- 核心问题是无法提前预估所需的
remaining_space,这可能导致频繁且开销高昂的重分配与复制操作。
指针转整数运算的标准限制
此前我考虑过将指针转换为std::uintptr_t后做整数运算,来检查或调整对齐、计算空间需求,无需使用std::align。但根据C++标准:
The value representation of pointer types is implementation-defined
仅数组内的指针运算有抽象定义,无法依赖reinterpret_cast<std::uintptr_t>(p)得到的整数值进行整数运算来计算对齐位置和所需缓冲区大小。
另外,关于「通过指针的整数值检查指针对齐是否良定义」的讨论也印证了这一点——直接依赖指针转整数后的运算判断对齐不符合标准,因为指针的数值表示由实现决定,无法保证跨平台一致性。
核心疑问
是否存在可移植且符合C++标准的方法,能够提前预估异构对象存储的空间需求?
内容的提问来源于stack exchange,提问作者Oersted
相关产品推荐
相关产品推荐

