Here is an example of allocator from cppreference:
#include <cstdlib>
#include <limits>
#include <new>
template<class T>
struct Mallocator
{
typedef T value_type;
Mallocator() = default;
template<class U>
constexpr Mallocator(const Mallocator<U>&) noexcept
{
}
[[nodiscard]] T* allocate(std::size_t n)
{
if (n > std::numeric_limits<std::size_t>::max() / sizeof(T))
throw std::bad_array_new_length();
if (auto p = static_cast<T*>(std::malloc(n * sizeof(T)))) {
return p;
}
throw std::bad_alloc();
}
void deallocate(T* p, std::size_t n) 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;
}
It can be used as in examples 1 and 2 in the following snippet:
#include "mallocator.h"
#include <vector>
int mainF()
{
std::vector<int, Mallocator<int>> v; // 1
Mallocator<int> a;
std::vector<int, Mallocator<int>> v2 { a }; // 2
std::vector<int, Mallocator<int>> v3 { a }; // 2
// std::vector<int> v4 { a }; // 3 (compilation error)
return 0;
}
Is it possible to conform custom allocator so it will work as in example 3. If yes, how to do it?
template<class T, class Allocator = MyAllocator<T> > using YourVector = std::vector<T, Allocator>;. But you can't just force all code that explicitly usesstd::vectorto default to using an allocator other thanstd::allocator<T>.