函数
<memory>

std::align

void* align (size_t alignment, size_t size, void*& ptr, size_t& space);
Align in range
Returns a pointer to the first possible address of the range of space bytes pointed by ptr where it is possible to fit size bytes of storage aligned as specified by alignment.

The function updates ptr to point to such address, and decreases space by the number of bytes used for alignment, so that these arguments can be used in repeated calls to this function.

If space is not enough to accommodate for the requested aligned buffer, the function returns a null pointer, and alters neither ptr nor space.

参数

alignment
Requested alignment, in bytes.
This shall be a valid alignment value supported by the platform in this context.
size_t 是一个无符号整数类型。
size
Size of the element to be aligned, in bytes.
size_t 是一个无符号整数类型。
ptr
Pointer to contiguous storage of at least space bytes.
This argument, passed by reference, is updated by the function.
space
Maximum size of the buffer to consider for alignment.
This argument, passed by reference, is updated by the function.
size_t 是一个无符号整数类型。

返回值

If the aligned buffer fits into the proposed space, the function returns the updated value of ptr. Otherwise, a null pointer is returned.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// align example
#include <iostream>
#include <memory>

int main() {
  char buffer[] = "------------------------";
  void * pt = buffer;
  std::size_t space = sizeof(buffer)-1;
  while ( std::align(alignof(int),sizeof(char),pt,space) ) {
    char* temp = static_cast<char*>(pt);
    *temp='*'; ++temp; space-=sizeof(char);
    pt=temp;
  }
  std::cout << buffer << '\n';
  return 0;
}

可能的输出
-*---*---*---*---*---*--


另见