为什么C++自定义分配器需要比较运算符?

jas*_*mar 5 c++ allocator c++-standard-library

在实现自定义C++分配器时,需要定义:

  • operator== 对于具有不同的分配器 value_type
  • operator!= 对于具有不同的分配器 value_type

您可以在Allocator概念文档中看到自定义分配器的示例实现:

#include <cstdlib>
#include <new>
template <class T>
struct Mallocator {
  typedef T value_type;
  Mallocator() = default;
  template <class U> constexpr Mallocator(const Mallocator<U>&) noexcept {}
  T* allocate(std::size_t n) {
    if(n > std::size_t(-1) / sizeof(T)) throw std::bad_alloc();
    if(auto p = static_cast<T*>(std::malloc(n*sizeof(T)))) return p;
    throw std::bad_alloc();
  }
  void deallocate(T* p, std::size_t) noexcept { std::free(p); }
};
template <class T, class U>
bool operator==(const Mallocator<T>&, const Mallocator<U>&) { return true; }
template <class T, class U>
bool operator!=(const Mallocator<T>&, const Mallocator<U>&) { return false; }
Run Code Online (Sandbox Code Playgroud)

问题是这两个运营商的目的是什么?他们什么时候被使用?

编辑:

请注意我不是问如何实现这样的运算符(在链接中解释),我问为什么有必要实现它们,所以当这些运算符被使用时.

Pet*_*ker 8

阅读有关分配器要求的信息.operator==告诉您其中一个分配器对象实例是否可以释放由另一个分配的对象实例.将一个容器的内容移动到另一个容器时,这很重要.如果第二个容器的分配器是==第一个容器的,那么通常可以通过交换一个或两个指针来进行移动,在第二个容器中重用第一个容器的内存.如果分配器不相等,则复制操作必须复制每个元素,根据需要在第二个容器中分配内存,并释放第一个容器保存的内存.