Skip to content

Instantly share code, notes, and snippets.

@mpapierski
Created May 26, 2013 20:43
Show Gist options
  • Save mpapierski/5653957 to your computer and use it in GitHub Desktop.
Save mpapierski/5653957 to your computer and use it in GitHub Desktop.
im not sure why i wrote this
#include <cstdlib>
#include <iostream>
#include <queue>
#include <stdexcept>
struct policy
{
};
struct allocator: policy
{
virtual void * allocate(std::size_t size) = 0;
};
struct heap_allocator: allocator
{
virtual void * allocate(std::size_t size)
{
std::cout << "stack allocating " << size << " bytes" << std::endl;
return std::malloc(size);
}
};
struct debug_allocator: allocator
{
virtual void * allocate(std::size_t size)
{
std::cout << "debug allocating " << size << " bytes" << std::endl;
return std::malloc(size);
}
};
static std::deque<allocator *> allocator_stack;
template <typename T>
struct use
{
use()
{
allocator_stack.push_back(new T());
}
~use()
{
T * back = static_cast<T *>(allocator_stack.back());
delete back;
allocator_stack.pop_back();
}
};
void * allocate(std::size_t size)
{
if (allocator_stack.empty())
{
throw std::runtime_error("There is no allocator on the stack!");
}
allocator * back = allocator_stack.back();
return back->allocate(size);
}
void hello_world()
{
use<heap_allocator> scope1;
char * data1 = static_cast<char *>(allocate(1024));
use<debug_allocator> scope2;
char * data2 = static_cast<char *>(allocate(1024));
}
int
main()
{
hello_world();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment