3 ms·
How about this? template<typename T> struct Foo { using value_type = T; Foo() = default; template<typename U> constexpr Foo(const Foo <U>
by menaerus 3y ago
How about this?
template<typename T>
struct Foo {
using value_type = T;
Foo() = default;
template<typename U>
constexpr Foo(const Foo <U>&) noexcept {}
T* allocate(std::size_t n) {
if (n > std::numeric_limits<std::size_t>::max() / sizeof(T))
throw std::bad_array_new_length();
auto p = static_cast<T*>(std::malloc(n * sizeof(T)));
if (!p) throw std::bad_alloc();
return p;
}
void deallocate(T* p, std::size_t n) noexcept {
std::free(p);
}
};
And then you go and use it as
std::vector<int, Foo<int>> v;
So the complexity is not really in writing the "C++ allocator" but in writing a sufficiently complex memory management logic that will actually make your application/algorithm run faster. And that only you can know given that you're familiar with the memory allocation patterns in your code. C++ allocator is only an interface that allows you to capture that logic and makes it feasible to apply through the code.