我想做的是NOT初始化一个与给定边界对齐的指针,相反,它就像一些函数,可以将指针(及其指向的内容)的物理地址来回转换/复制到一个对齐的内存地址,就像下面代码中的alignedPtr()
:
void func(double * x, int len)
{
//Change x's physical address to an aligned boundary and shift its data accordingly.
alignedPtr(x, len);
//do something...
};
假设分配的缓冲区大小足够大,即需要len
+对齐,则实现将需要2个步骤。
-
newPtr = ((orgPtr + (ALIGNMENT - 1)) & ALIGN_MASK);
-这将生成新的指针 -
由于预期的设计是就地计算,因此从
newPtr + len
向后复制以避免覆盖数据。
在C++11中,您可以使用稍微令人困惑的来使用std::align
。
void* new_ptr = original_ptr;
std::size_t space_left = existing_space;
if(!std::align(desired_alignment, size_of_data, new_ptr, space_left)) {
// not enough space; deal with it
}
// now new_ptr is properly aligned
// and space_left is the amount of space left after aligning
// ensure we have enough space left
assert(space_left >= size_of_data);
// now copy from original_ptr to new_ptr
// taking care for the overlapping ranges
std::memove(new_ptr, original_ptr, size_of_data);