始于c++11,c++23弃用
aligned_storage 是 C++ 标准库中用于管理对齐内存的模板类,定义在 <type_traits> 头文件中。它通过模板参数指定内存大小和对齐方式,提供未初始化的内存区域,适用于需要精确控制内存布局的场景。
核心功能
内存对齐管理:通过模板参数设置内存大小(Len)和对齐方式(Align),确保数据按特定规则排列。
类型安全保障:提供 type 类型别名,避免直接操作未初始化内存导致的未定义行为。
应用场景:
实现自定义容器(如 :ml-search-more[std::optional]、:ml-search-more[std::variant] 等)。
手动管理内存时保持布局一致性
#include <type_traits> #include <iostream> typedef std::aligned_storage<sizeof(int), std::alignment_of<double>::value>::type new_type; int main() {std::cout << "alignment_of<int> == " << std::alignment_of<int>::value << std::endl;std::cout << "aligned to double == " << std::alignment_of<new_type>::value << std::endl;return 0; }
https://stackoverflow.com/questions/71828288/why-is-stdaligned-storage-to-be-deprecated-in-c23-and-what-to-use-instead
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p1413r3.pdf