Namespaces
Variants

std:: align

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
定义于头文件 <memory>
void * align ( std:: size_t alignment,

std:: size_t size,
void * & ptr,

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

给定一个指向大小为 space 的缓冲区的指针 ptr ,返回按指定 alignment 对齐的指针,用于 size 字节数,并减少 space 参数的值,减少量为用于对齐的字节数。返回第一个对齐地址。

该函数仅在缓冲区能够容纳按指定对齐方式对齐的所需字节数时修改指针。若缓冲区过小,函数将不执行任何操作并返回 nullptr

如果 alignment 不是2的幂,则行为未定义。

目录

参数

alignment - 所需的对齐要求
size - 待对齐存储空间的大小
ptr - 指向至少具有 space 字节的连续存储空间(缓冲区)的指针
space - 操作缓冲区的总大小

返回值

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

示例

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

#include <iostream>
#include <memory>
#include <new>
template<std::size_t N>
struct MyAllocator
{
    std::byte data[N];
    std::size_t sz{N};
    void* p{data};
    MyAllocator() = default;
    // Note: only well-defined for implicit-lifetime types
    template<typename T>
    T* implicit_aligned_alloc(std::size_t a = alignof(T))
    {
        if (std::align(a, sizeof(T), p, sz))
        {
            T* result = std::launder(reinterpret_cast<T*>(p));
            p = static_cast<std::byte*>(p) + sizeof(T);
            sz -= sizeof(T);
            return result;
        }
        return nullptr;
    }
};
int main()
{
    MyAllocator<64> a;
    std::cout << "allocated a.data at " << (void*)a.data
              << " (" << sizeof a.data << " bytes)\n";
    // Allocate a char
    if (char* p = a.implicit_aligned_alloc<char>())
    {
        *p = 'a';
        std::cout << "allocated a char at " << (void*)p << '\n';
    }
    // Allocate an int
    if (int* p = a.implicit_aligned_alloc<int>())
    {
        *p = 1;
        std::cout << "allocated an int at " << (void*)p << '\n';
    }
    // Allocate an int, aligned at a 32-byte boundary
    if (int* p = a.implicit_aligned_alloc<int>(32))
    {
        *p = 2;
        std::cout << "allocated an int at " << (void*)p << " (32-byte alignment)\n";
    }
}

可能的输出:

allocated a.data at 0x7ffc654e8530 (64 bytes)
allocated a char at 0x7ffc654e8530
allocated an int at 0x7ffc654e8534
allocated an int at 0x7ffc654e8540 (32-byte alignment)

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 适用范围 发布时的行为 正确行为
LWG 2377 C++11 alignment 要求为基础对齐值或受支持的扩展对齐值 仅需为2的幂次

参见

alignof (C++11) 查询类型的对齐要求
(运算符)
alignas (C++11) 指定变量的存储应按特定量对齐
(说明符)
(since C++11) (deprecated in C++23)
定义适合用作给定大小类型的未初始化存储的类型
(类模板)
告知编译器指针已对齐
(函数模板)