首页 > 解决方案 > std::aligned_storage 的目的是什么?

问题描述

如果我理解正确,它的主要优点std::aligned_storage是它管理对齐。memcpy()它也可以与 POD 类型一起复制和使用。

但!

1) POD 类型默认由编译器对齐,我们可以使用覆盖此编译器的对齐方式#pragma pack(push, 1)

2)我们可以默认复制POD memcpy()(我们不应该为这个能力做点什么)

所以我真的不明白我们为什么需要std::aligned_storage

标签: c++c++11std

解决方案


您可以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构造了 ,就会立即为Ntype 的对象分配内存T,但还没有T创建 type 的对象。

你不能用一个简单的T data[N];数组成员来做到这一点,因为这会立即T为每个元素运行 's 的构造函数,或者如果T不是默认可构造的,甚至不会编译。


推荐阅读