memgraph/poc/memory/allocator.hpp

44 lines
899 B
C++
Raw Normal View History

#pragma once
2015-06-22 20:31:26 +08:00
#include <cstdlib>
#include <new>
template <class Tp>
struct fast_allocator {
typedef Tp value_type;
2015-06-22 20:31:26 +08:00
fast_allocator() = default;
2015-06-22 20:31:26 +08:00
template <class T>
fast_allocator(const fast_allocator<T>&) {}
Tp* allocate(std::size_t n);
void deallocate(Tp* p, std::size_t n);
2015-06-22 20:31:26 +08:00
};
template <class Tp>
Tp* fast_allocator<Tp>::allocate(std::size_t n) {
// hopefully we're using jemalloc here!
Tp* mem = static_cast<Tp*>(malloc(n * sizeof(Tp)));
2015-06-22 20:31:26 +08:00
if (mem != nullptr) return mem;
2015-06-22 20:31:26 +08:00
throw std::bad_alloc();
2015-06-22 20:31:26 +08:00
}
template <class Tp>
void fast_allocator<Tp>::deallocate(Tp* p, std::size_t) {
// hopefully we're using jemalloc here!
free(p);
2015-06-22 20:31:26 +08:00
}
template <class T, class U>
bool operator==(const fast_allocator<T>&, const fast_allocator<U>&) {
return true;
2015-06-22 20:31:26 +08:00
}
template <class T, class U>
bool operator!=(const fast_allocator<T>& a, const fast_allocator<U>& b) {
return !(a == b);
2015-06-22 20:31:26 +08:00
}