align
将给定大小的存储(通过给定对齐规范对齐)放入给定存储的第一个可能地址。
void* align(
size_t Alignment, // input
size_t Size, // input
void*& Ptr // input/output
size_t& Space // input/output
);
参数
Alignment
要尝试的对齐边界。Size
对齐存储的大小(以字节为单位)。Ptr
要使用的可用连续存储池的起始地址。 此参数还用作输出参数,如果对齐成功,将包含新的起始地址。如果 align() 不成功,则不修改此参数。
Space
供 align() 用于创建对齐存储的总空间。 此参数还是输出参数,并包含存储缓冲区中在减去对齐存储和任何关联系统开销后剩余的调整空间。如果 align() 不成功,则不修改此参数。
返回值
如果请求的对齐缓冲区无法放入可用空间,则为 null 指针;否则为 Ptr 的新值。
备注
通过修改的 Ptr 和 Space 参数,可以使用不同的 Alignment 值和 Size 值,对同一缓冲区重复调用 align()。 下面的代码片段演示 align() 的一种用法。
#include <type_traits> // std::alignment_of()
#include <memory>
//...
char buffer[256]; // for simplicity
size_t alignment = std::alignment_of<int>::value;
void * ptr = buffer;
std::size_t space = sizeof(buffer); // Be sure this results in the true size of your buffer
while (alignment, sizeof(MyObj), ptr, space)) {
// You now have storage the size of MyObj, starting at ptr, aligned on
// int boundary. Use it here if you like, or save off the starting address
// contained in ptr for later use.
// ...
// Last, move starting pointer and decrease available space before
// the while loop restarts.
ptr = reinterpret_cast<char*>(ptr) + sizeof(MyObj);
space -= sizeof(MyObj);
}
// At this point, align() has returned a null pointer, signaling it is not
// possible to allow more aligned storage in this buffer.
要求
标头:<memory>
命名空间: std