std::align
From cppreference.com
| ヘッダ <memory> で定義 |
||
| void* align( std::size_t alignment, std::size_t size, |
(C++11以降) | |
指定された alignment でアライメントされた、size バイトの領域を指すポインタをバッファ ptr (サイズ space) から取得し、アライメントに使用されたバイト数だけ space 引数を減少させます。最初のアライメントされたアドレスが返されます。
この関数は、指定されたアライメントで要求されたバイト数をバッファに格納できる場合にのみ、ポインタを変更します。バッファが小さすぎる場合、関数は何もせず nullptr を返します。
alignment が2のべき乗でない場合、動作は未定義です。
目次 |
[編集] パラメータ
| alignment | - | 目的のアライメント |
| size | - | アライメントされるストレージのサイズ |
| ptr | - | 少なくとも 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; MyAllocator() : p(data) {} // 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) |
変数用のストレージを特定の量でアラインすることを指定します。 (指定子) |
| (C++11以降)(C++23で非推奨) |
与えられたサイズの型の未初期化ストレージとして使用するのに適した型を定義する (クラステンプレート) |
| (C++20) |
ポインタがアラインされていることをコンパイラに伝えます (関数テンプレート) |