std::align
來自 cppreference.com
定義於標頭檔案 <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; 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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2377 | C++11 | alignment 要求是基本型別或受支援的擴充套件對齊值 |
只需是 2 的冪 |
[編輯] 另請參閱
alignof (C++11) |
查詢型別的對齊要求 (運算子) |
alignas (C++11) |
指定變數的儲存應按特定量對齊 (說明符) |
(自 C++11)(C++23 中已棄用) |
定義適合用作給定大小型別的未初始化儲存的型別 (類模板) |
(C++20) |
通知編譯器指標已對齊 (函式模板) |