union 而不是 aligned_storage_t 作为容器节点类型的一部分

union instead of aligned_storage_t as part of node type of container

容器std::list< T >/std::map< T >/std::set< T >(非完整列表)存储元素使用节点类型,这与T不同,例如std::vectorstd::array.

如果我将一些分配器 A 传递给他们,那么它将通过类似以下的方式从 "converted" 到 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++) may use an analogue of std::aligned_storage_t< sizeof(T), alignof(T) > 作为 节点类型的组成部分 作为存储类型 T 值的位置。"Past the end"或 "root" 元素可能没有存储类型 T 的值。该值的生命周期 "manually" 由容器通过使用就地 ::operator new 和手动进行管理最后调用析构函数。

在表单

中使用单元素union是否有效
union U
{
    U() { ; }
    T value;
};

而不是 std::aligned_storage_t< sizeof(T), alignof(T) >?

std::aligned_storage_t 的哪些属性(在内部它可以实现为 char [sizeof(T)]; 类型的正确对齐数组)在提到的用例中是至关重要的,并且优于上述 [=] 的所有潜在优势23=]?

首先,比较接近的类比其实是:

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 更符合人体工程学。