Skip to content

Instantly share code, notes, and snippets.

@rmartinho
Created April 17, 2013 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmartinho/5405354 to your computer and use it in GitHub Desktop.
Save rmartinho/5405354 to your computer and use it in GitHub Desktop.
Just a sample of what kind of magic I think could make a C++ alloca().
// Usage:
// int f(int n) {
// auto buf = stack_alloc<int>(n);
// std::iota(buf.begin(), buf.end());
// return std::sum(buf.begin(), buf.end());
// }
// allocation function
template <typename T>
stack_array_ref<T> stack_alloc(size_t size) __magic_works_like_a_macro_to_use_the_right_frame__;
// could be simply array_ref, but let's try going overboard with safety
template <typename T>
struct stack_array_ref {
public:
T* data() const { return ptr; }
size_t size() const { return sz; }
using iterator = T*;
using const_iterator = T const*;
iterator begin() { return ptr; }
iterator end() { return ptr+sz; }
const_iterator begin() const { return ptr; }
const_iterator end() const { return ptr+sz; }
private:
// only the compiler can use this
stack_array_ref(T* ptr, size_t sz) : ptr(ptr), sz(sz);
// it's a brick, only the compiler can take it out of the function you place it on
stack_array_ref(stack_array_ref&&) = default;
stack_array_ref& operator=(stack_array_ref&&) = default;
friend stack_array_ref<T> stack_alloc<T>(size_t size) __magic_works_like_a_macro_to_use_the_right_frame__;
T* ptr;
size_t sz;
};
// MAGIC happens here
template <typename T>
stack_array_ref<T> stack_alloc(size_t size) __magic_works_like_a_macro_to_use_the_right_frame__ {
return { ::new(alloca(size*sizeof(T))) T[size], size };
// I know placement-array-new is broken, but the compiler has the magic!
// While at it, the compiler can also align the damn thing properly :P
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment