std::align

定义于头文件 <memory>
void* align( std::size_t alignment,

             std::size_t size,
             void*& ptr,

             std::size_t& space );
(C++11 起)

给定指针 ptr 指定大小为 space 的缓冲区,返回按指定 alignmentsize 字节数对齐的指针,并减小 space 参数对齐所用的字节数。返回首个对齐的地址。

仅以给定对齐量对齐入缓冲区的所需字节数合适,函数才会修改指针。若缓冲区太小,则函数不做任何事并返回 nullptr

alignment 不是实现支持的基础或扩展对齐值 (C++17 前)二的幂 (C++17 起),则行为未定义。

目录

参数

alignment - 欲求的对齐量
size - 要被对齐的存储的大小
ptr - 指向至少有 space 字节的连续存储的指针
space - 要在其中操作的缓冲区的大小

返回值

ptr 的调整值,或若提供空间太小则为空指针值。

示例

演示使用 std::align 在内存中放置不同类型的对象

#include <iostream>
#include <memory>
 
template <std::size_t N>
struct MyAllocator
{
    char data[N];
    void* p;
    std::size_t sz;
    MyAllocator() : p(data), sz(N) {}
    template <typename T>
    T* aligned_alloc(std::size_t a = alignof(T))
    {
        if (std::align(a, sizeof(T), p, sz))
        {
            T* result = reinterpret_cast<T*>(p);
            p = (char*)p + sizeof(T);
            sz -= sizeof(T);
            return result;
        }
        return nullptr;
    }
};
 
int main()
{
    MyAllocator<64> a;
 
    // 分配一个 char
    char* p1 = a.aligned_alloc<char>();
    if (p1)
        *p1 = 'a';
    std::cout << "allocated a char at " << (void*)p1 << '\n';
 
    // 分配一个 int
    int* p2 = a.aligned_alloc<int>();
    if (p2)
        *p2 = 1;
    std::cout << "allocated an int at " << (void*)p2 << '\n';
 
    // 分配一个 int ,对齐于 32 字节边界
    int* p3 = a.aligned_alloc<int>(32);
    if (p3)
        *p3 = 2;
    std::cout << "allocated an int at " << (void*)p3 << " (32 byte alignment)\n";
}

可能的输出:

allocated a char at 0x2ff21a08
allocated an int at 0x2ff21a0c
allocated an int at 0x2ff21a20 (32 byte alignment)

参阅

alignof 运算符 查询类型的对齐要求 (C++11 起)
alignas 指定符 指定该变量的存储应该按指定量对齐 (C++11)
定义适用作给定大小的类型的未初始化存储的类型
(类模板)

版本历史

  • (当前 | 先前 2017年5月2日 (二) 09:34Fruderica讨论 | 贡献. . (2,606字节) (+588). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 17:55P12bot讨论 | 贡献 . . (2,018字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:00P12bot讨论 | 贡献 . . (2,018字节) (-117). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 17:16P12bot讨论 | 贡献 . . (2,135字节) (+193). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 03:24P12讨论 | 贡献 . . (1,942字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,942字节) (-59). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:08P12讨论 | 贡献 . . (2,001字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (2,001字节) (+2,001). . (Translated from the English version using Google Translate)