Skip to content

Instantly share code, notes, and snippets.

@tylorr
Created September 23, 2017 06:19
Show Gist options
  • Save tylorr/33e84cf68fb56a2631f2e97ff828b728 to your computer and use it in GitHub Desktop.
Save tylorr/33e84cf68fb56a2631f2e97ff828b728 to your computer and use it in GitHub Desktop.
template <typename T>
class stack_array {
public:
__attribute__((always_inline)) stack_array(size_t length)
: ptr_{new (static_cast<T *>(alloca(sizeof(T) * length))) T[length]},
length_{length} {}
~stack_array() {
for (size_t i = 0; i < length_; ++i) {
ptr_[i].~T();
}
}
operator T *() { return ptr_; }
size_t size() { return length_; }
using iterator = T *;
iterator begin() { return ptr_; }
iterator end() { return ptr_ + length_; }
private:
T *ptr_;
size_t length_;
};
@tylorr
Copy link
Author

tylorr commented Sep 23, 2017

Too bad __attribute__((always_inline)) doesn't apply unless you have -O1 or greater (clang version 4.0.0).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment