While implementing custom C++ allocator, one needs to define:
operator==
for the allocator with differentvalue_type
operator!=
for the allocator with differentvalue_type
You can see the example implementation of custom allocator in documentation of Allocator concept:
#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; }
The question is what are purposes of those 2 operators? When are they being used?
EDIT:
Please note I am not asking how to implement such operators (explained in the link), I am asking why it is necessary to implement them, so when those are being used.
operator==
function. returns true only if the storage allocated by the allocator a1 can be deallocated through a2. Establishes reflexive, symmetric, and transitive relationship. Does not throw exceptions. Is that not sufficient explanation? – Dappled