◐ Shell
clean mode source ↗

std::align - cppreference.com

提供: cppreference.com

<tbody> </tbody>

void* align( std::size_t alignment, std::size_t size, void*& ptr, std::size_t& space );

(C++11以上)

サイズ space のバッファを指すポインタ ptr が与えられたとき、 size 個のバイトの指定された alignment によってアラインされたポインタを返し、 space 引数をアライメントのために使用されたバイト数だけ減少させます。 最初のアラインされたアドレスが返されます。

この関数は、指定されたアライメントによってアラインされた所望のバイト数をバッファに収めることができるであろう場合にのみ、ポインタを変更します。 バッファが小さすぎる場合、この関数は何もせず、 nullptr を返します。

alignment が2の乗数でなければ、動作は未定義です。

引数

alignment - 所望のアライメント
size - アラインされる記憶域のサイズ
ptr - 少なくとも space バイトの連続する記憶域へのポインタ
space - 操作するバッファのサイズ

戻り値

ptr の調節された値、または提供された空間が小さすぎる場合はmヌルポインタ値。

メモリ内に異なる型のオブジェクトを配置するための 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;

    // allocate a char
    char* p1 = a.aligned_alloc<char>();
    if (p1)
        *p1 = 'a';
    std::cout << "allocated a char at " << (void*)p1 << '\n';

    // allocate an int
    int* p2 = a.aligned_alloc<int>();
    if (p2)
        *p2 = 1;
    std::cout << "allocated an int at " << (void*)p2 << '\n';

    // allocate an int, aligned at 32-byte boundary
    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)

欠陥報告

以下の動作変更欠陥報告は以前に発行された C++ 標準に遡って適用されました。

DR 適用先 発行時の動作 正しい動作
LWG 2377 C++11 alignment required to be a fundamental or supported extended alignment value only need to be a power of two

関連項目