Skip to content

Instantly share code, notes, and snippets.

@unrays
Created January 19, 2026 12:51
Show Gist options
  • Select an option

  • Save unrays/6661364c8e5d7428e0bdb74a5cb48353 to your computer and use it in GitHub Desktop.

Select an option

Save unrays/6661364c8e5d7428e0bdb74a5cb48353 to your computer and use it in GitHub Desktop.
Basic C++ template allocator example
// Copyright (c) December 2025 Félix-Olivier Dumas. All rights reserved.
// Licensed under the terms described in the LICENSE file
#include <iostream>
struct Point {
int x, y;
Point(int a, int b) : x(a), y(b) {}
void print() { std::cout << "(" << x << "," << y << ")\n"; }
};
template<typename T>
struct Allocator {
T* allocate(std::size_t n) {
return static_cast<T*>(::operator new(sizeof(T) * n));
}
void deallocate(T* ptr, std::size_t n) {
::operator delete(ptr);
}
template<typename... Args>
void construct(T* ptr, Args&&... args) {
new (ptr) T(std::forward<Args>(args)...);
}
void destroy(T* ptr) {
ptr->~T();
}
std::size_t max_size() const {
return std::numeric_limits<std::size_t>::max() / sizeof(T);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment