std:: align
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
定義先ヘッダ
<memory>
|
||
|
void
*
align
(
std::
size_t
alignment,
std::
size_t
size,
|
(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)
|
変数のストレージが特定の量でアラインされることを指定する
(指定子) |
|
(C++11以降)
(C++23で非推奨)
|
指定されたサイズの型の未初期化ストレージとして使用するのに適した型を定義する
(クラステンプレート) |
|
(C++20)
|
ポインタがアラインされていることをコンパイラに通知する
(関数テンプレート) |