c++ - std::aligned_storage 的目的是什么?
问题描述
如果我理解正确,它的主要优点std::aligned_storage
是它管理对齐。memcpy()
它也可以与 POD 类型一起复制和使用。
但!
1) POD 类型默认由编译器对齐,我们可以使用覆盖此编译器的对齐方式#pragma pack(push, 1)
2)我们可以默认复制POD memcpy()
(我们不应该为这个能力做点什么)
所以我真的不明白我们为什么需要std::aligned_storage
?
解决方案
您可以std::aligned_storage
在希望将内存分配与对象创建分离时使用。
您声称:
此外,它仅可用于 POD 类型。
但是这是错误的。没有什么可以阻止std::aligned_storage
与非 POD 类型一起使用。
cppreference 上的示例提供了一个合法的用例:
template<class T, std::size_t N> class static_vector { // properly aligned uninitialized storage for N T's typename std::aligned_storage<sizeof(T), alignof(T)>::type data[N]; std::size_t m_size = 0; ...
这里的想法是,一旦static_vector
构造了 ,就会立即为N
type 的对象分配内存T
,但还没有T
创建 type 的对象。
你不能用一个简单的T data[N];
数组成员来做到这一点,因为这会立即T
为每个元素运行 's 的构造函数,或者如果T
不是默认可构造的,甚至不会编译。
推荐阅读
- c - exec* POSIX 函数中的管道
- python - 根据匹配的列标签将行值添加到数据框中
- batch-file - 批量修改代理设置不起作用
- asp.net - asp引导选择不起作用
- c# - UWP AppServiceConnection - SendResponseAsync 返回 AppServiceResponseStatus.Failure
- c++ - 从部分专用的模板方法调用模板非静态方法
- python - 使用 int8 列检查 pandas 数据框中的 NaN 值
- html - 范围滑块拇指未在 IE 上显示
- python - python anaconda Py_Initialize:无法初始化 sys 标准流 LookupError:未知编码:65001
- java - java.util.zip“找不到文件”错误