我试图理解如何正确编写 AllocatorAware 容器。
我的理解是,propagate_on_container_move_assignment
typedef 指示是否需要在容器自身被 move-assigned 时复制某个 Allocator
类型。
因此,由于我找不到任何示例,我自己尝试了以下内容:
给定容器类型 Container
,一个 Allocator
类型 allocator_type
和一个内部的 allocator_type
数据成员 m_alloc
:
Container& operator = (Container&& other)
{
if (std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value)
{
m_alloc = std::allocator_traits<allocator_type>::select_on_container_copy_construction(
other.m_alloc
);
}
return *this;
}
这是否正确?
此外,这里另一个令人困惑的来源是嵌套的 typedefs propagate_on_container_move/copy_assignment
是在特别讨论 赋值操作 ... 但是构造函数呢?AllocatorAware
容器的移动构造函数或拷贝构造函数 也需要 检查这些 typedefs 吗?我认为答案应该是 是的... 这意味着,我还需要写:
Container(Container&& other)
{
if (std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value)
{
m_alloc = std::allocator_traits<allocator_type>::select_on_container_copy_construction(
other.m_alloc
);
}
}
propagate_on_move_assignment
为真,但是lhs和rhs的分配器比较不相等怎么办?如果propagate_on_move_assignment
为真,我们不应该先检查分配器是否相等吗?如果它们相等,我们就不需要在移动分配分配器之前释放所有内存。(这样我们就可以重用已经分配的内存) - Silerif constexpr
来分离{1}和{2,3}。 - zjyhjqs