Skip to content

Instantly share code, notes, and snippets.

@pebble8888
Created March 11, 2017 14:44
Show Gist options
  • Select an option

  • Save pebble8888/f7af6dabd4a522a79e8d40a6bafbadfa to your computer and use it in GitHub Desktop.

Select an option

Save pebble8888/f7af6dabd4a522a79e8d40a6bafbadfa to your computer and use it in GitHub Desktop.
C++ allocator sample
#include <cstdlib>
template <class T>
struct MyAllocator {
using value_type = T;
// default constractor
// copy constractor
// move constractor
MyAllocator()
{
}
template <class U>
MyAllocator(const MyAllocator<U>&)
{
}
T* allocate(std::size_t n)
{
return reinterpret_cast<T*>(std::malloc(sizeof(T) * n));
}
void deallocate(T* p, std::size_t n)
{
static_cast<void>(n);
std::free(p);
}
};
// compare operator
template <class T, class U>
bool operator==(const MyAllocator<T>&, const MyAllocator<U>&)
{
return true;
}
template <class T, class U>
bool operator!=(const MyAllocator<T>&, const MyAllocator<U>&)
{
return false;
}
#include <vector>
#include <list>
int main()
{
std::vector<int, MyAllocator<int>> v = {1, 2, 3};
std::list<int, MyAllocator<int>> ls = {4, 5, 6};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment