jas*_*mar 5 c++ allocator c++-standard-library
在实现自定义C++分配器时,需要定义:
operator== 对于具有不同的分配器 value_typeoperator!= 对于具有不同的分配器 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)
问题是这两个运营商的目的是什么?他们什么时候被使用?
编辑:
请注意我不是问如何实现这样的运算符(在链接中解释),我问为什么有必要实现它们,所以当这些运算符被使用时.