std :: aligned_storage的目的是什么? [英] What is the purpose of std::aligned_storage?
问题描述
如果我理解正确的话, std :: aligned_storage
的主要优点是它可以管理对齐方式。也可以使用 memcpy()
复制它,并可以与POD类型一起使用。
If I understand it correctly, the main advantage of the std::aligned_storage
is that it manages the alignment. Also it can be copied with memcpy()
and can be used with POD types.
但是!
1)默认情况下,编译器会对齐POD类型,我们可以使用 #pragma pack(push,1)覆盖此编译器的对齐方式
1) The POD types are aligned by compiler by default and we can override this compiler's alignment using #pragma pack(push, 1)
2)默认情况下,我们可以使用 memcpy()
复制POD(我们不应该
2) We can copy POD with memcpy()
by default (we shouldn't do something for this ability)
所以我真的不明白为什么我们需要 std :: aligned_storage
?
So I don't really understand why do we need std::aligned_storage
?
推荐答案
只要想取消耦合,就可以使用 std :: aligned_storage
You can use std::aligned_storage
whenever you wish to decouple memory allocation from object creation.
您声称:
也可以使用
Also it is usable only with POD types.
但这不是事实。没有什么能阻止 std :: aligned_storage
与非POD类型一起使用。
But this is not true. There is nothing preventing std::aligned_storage
from being used with non-POD types.
关于cppreference的示例提供了一个合法的用例:
The example on cppreference provides a legitimate use case:
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
,立即为 T $类型的
N
个对象分配内存。 c $ c>,但尚未创建类型为 T
的对象。
The idea here is that once the static_vector
is constructed, memory is immediately allocated for N
objects of type T
, but no objects of type T
are created yet.
您无法使用简单的方法 T data [N];
数组成员,因为它将立即为每个元素运行 T
的构造函数,否则即使 T
不是默认可构造的,甚至都不会编译。
You cannot do that with a simple T data[N];
array member, because this would immediately run T
's constructor for each element, or wouldn't even compile if T
is not default-constructible.
这篇关于std :: aligned_storage的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!