容器 std::list< T >/std::map< T >/std::set< T >
(不是完整列表)存储元素使用节点类型,这不同于T
,与 std::vector
相反或 std::array
.
如果我传递一些分配器 A
给他们,然后它将“转换”为 node_allocator_type
通过类似的方式:
using allocator_traits = typename std::allocator_traits< A >::template rebind_traits< node_type >;
using node_allocator_type = typename allocator_traits::allocator_type;
标准库实现( libc++ , libstdc++ )可以使用 std::aligned_storage_t< sizeof(T), alignof(T) >
的类似物作为节点类型的组成部分 作为存储 T
类型值的地方. “结束”或“根”元素可能没有存储 T
类型的值.值的生命周期由容器通过就地使用“手动”管理 ::operator new
最后手动调用析构函数。
使用单元素有效吗union
形式
union U
{
U() { ; }
T value;
};
而不是 std::aligned_storage_t< sizeof(T), alignof(T) >
?
std::aligned_storage_t
的哪些属性(在内部它可能被实现为类型为 char [sizeof(T)];
的正确对齐的数组)在提到的用例中是至关重要的,并且胜过上述 union
的所有潜在优势。 ?
最佳答案
首先,更接近的类比其实是:
union U
{
U() { }
~U() { }
T value;
};
以防 T
不可轻易破坏。
也就是说,union
在您需要文字类型时是必需的。不能在 constexpr
构造函数中使用 placement-new,所以一开始就是这样。这是在这个方向上的巨大胜利。
aligned_storage_t
的一个优点是您无需担心 T
重载 operator&()
的可能性。 new (&u.value) T
可能会做一些奇怪的事情并且可能根本无法编译。 new (&storage) T
没有这个问题,同时比 new (std::addressof(u.value)) T
更符合人体工程学。
关于c++ - union 而不是 aligned_storage_t 作为容器节点类型的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42540198/