stack_array.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #pragma once
  2. #include "range_ops.h"
  3. #include <util/generic/array_ref.h>
  4. #include <util/system/defaults.h> /* For alloca. */
  5. namespace NStackArray {
  6. /**
  7. * A stack-allocated array. Should be used instead of � variable length
  8. * arrays that are not part of C++ standard.
  9. *
  10. * Example usage:
  11. * @code
  12. * void f(int size) {
  13. * // T array[size]; // Wrong!
  14. * TStackArray<T> array(ALLOC_ON_STACK(T, size)); // Right!
  15. * // ...
  16. * }
  17. * @endcode
  18. *
  19. * Note that it is generally a *VERY BAD* idea to use this in inline methods
  20. * as those might be called from a loop, and then stack overflow is in the cards.
  21. */
  22. template <class T>
  23. class TStackArray: public TArrayRef<T> {
  24. public:
  25. inline TStackArray(void* data, size_t len)
  26. : TArrayRef<T>((T*)data, len)
  27. {
  28. NRangeOps::InitializeRange(this->begin(), this->end());
  29. }
  30. inline ~TStackArray() {
  31. NRangeOps::DestroyRange(this->begin(), this->end());
  32. }
  33. };
  34. }
  35. #define ALLOC_ON_STACK(type, n) alloca(sizeof(type) * (n)), (n)