Created
May 26, 2013 20:43
-
-
Save mpapierski/5653957 to your computer and use it in GitHub Desktop.
im not sure why i wrote this
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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