相关疑难解决方法(0)

CRTP避免动态多态

如何在C++中使用CRTP来避免虚拟成员函数的开销?

c++ virtual templates crtp

88
推荐指数
3
解决办法
3万
查看次数

propagate_on_container_move_assignment的示例用法

我试图了解如何正确编写AllocatorAware容器.

我的理解是propagate_on_container_move_assignmenttypedef表示Allocator当Container本身被移动分配时是否需要复制某种类型.

所以,既然我找不到任何这方面的例子,我自己的抨击就像下面这样:

给定容器类型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;
}
Run Code Online (Sandbox Code Playgroud)

它是否正确?

此外,另一个混乱的来源是嵌套的typedef propagate_on_container_move/copy_assignment专门讨论赋值 ...但是构造函数呢?移动构造函数或AllocatorAware容器的复制构造函数是否需要检查这些typedef?我认为这里的答案是肯定的 ......意思是,我还需要写:

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
         );
      }
}
Run Code Online (Sandbox Code Playgroud)

c++ allocator c++11

18
推荐指数
1
解决办法
2488
查看次数

标签 统计

c++ ×2

allocator ×1

c++11 ×1

crtp ×1

templates ×1

virtual ×1