arena.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef EXECUTABLE_SEMANTICS_COMMON_ARENA_H_
  5. #define EXECUTABLE_SEMANTICS_COMMON_ARENA_H_
  6. #include <memory>
  7. #include <vector>
  8. #include "executable_semantics/common/nonnull.h"
  9. namespace Carbon {
  10. class Arena {
  11. public:
  12. // Allocates an object in the arena, returning a pointer to it.
  13. template <typename T, typename... Args>
  14. auto New(Args&&... args) -> Nonnull<T*> {
  15. auto smart_ptr =
  16. std::make_unique<ArenaEntryTyped<T>>(std::forward<Args>(args)...);
  17. Nonnull<T*> ptr = smart_ptr->Instance();
  18. arena_.push_back(std::move(smart_ptr));
  19. return ptr;
  20. }
  21. private:
  22. // Virtualizes arena entries so that a single vector can contain many types,
  23. // avoiding templated statics.
  24. class ArenaEntry {
  25. public:
  26. virtual ~ArenaEntry() = default;
  27. };
  28. // Templated destruction of a pointer.
  29. template <typename T>
  30. class ArenaEntryTyped : public ArenaEntry {
  31. public:
  32. template <typename... Args>
  33. explicit ArenaEntryTyped(Args&&... args)
  34. : instance_(std::forward<Args>(args)...) {}
  35. auto Instance() -> Nonnull<T*> { return Nonnull<T*>(&instance_); }
  36. private:
  37. T instance_;
  38. };
  39. // Manages allocations in an arena for destruction at shutdown.
  40. std::vector<std::unique_ptr<ArenaEntry>> arena_;
  41. };
  42. } // namespace Carbon
  43. #endif // EXECUTABLE_SEMANTICS_COMMON_ARENA_H_