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

标签 c++ stl containers unions c++17

容器 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/

相关文章:

c++ - 如何在 C 中使用 C++ 对象?

c++ - 结构在单独的头文件中导致 C++ 中的问题

c++ - 将 vector 作为数组传递是否安全?

kubernetes - CloudFoundry 是否支持每个应用程序使用多个容器?

layout - Flutter 布局容器边距

c++ - 是否可以使用 Wojciech Mula 算法对 __m256i 进行 popcount 并将结果存储在 8 个 32 位字而不是 4 个 64 位字中?

c++ - 找到另一个 map 内 vector 的公共(public)元素

c++ - 将 deque 转换到 void 指针和从 void 指针安全吗?

c++ - "Bus error"从结构访问集合<int>

azure - Azure WebApp 和 SQLAzure 上的 Sonarqube 容器