【发布时间】:2015-02-12 18:46:18
【问题描述】:
我正在尝试了解如何正确编写 AllocatorAware 容器。
我的理解是propagate_on_container_move_assignment typedef表示在Container本身被移动赋值时是否需要复制某个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;
}
这是正确的吗?
另外,这里的另一个混淆来源是嵌套的 typedef propagate_on_container_move/copy_assignment 专门谈论 assignment...但是构造函数呢? AllocatorAware 容器的移动构造函数或复制构造函数也需要检查这些类型定义吗?我认为这里的答案是 yes...,意思是,我还需要写:
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
);
}
}
【问题讨论】: