ptr.h 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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_PTR_H_
  5. #define EXECUTABLE_SEMANTICS_COMMON_PTR_H_
  6. #include <memory>
  7. #include <vector>
  8. #include "common/check.h"
  9. namespace Carbon {
  10. // A non-nullable pointer. Written as `Ptr<T>` instead of `T*`.
  11. template <typename T>
  12. class Ptr {
  13. public:
  14. explicit Ptr(T* ptr) : ptr(ptr) { CHECK(ptr != nullptr); }
  15. template <typename OtherT,
  16. std::enable_if_t<std::is_convertible_v<OtherT*, T*>>* = nullptr>
  17. Ptr(Ptr<OtherT> other) {
  18. return Ptr<OtherT>(other.ptr);
  19. }
  20. Ptr(std::nullptr_t) = delete;
  21. Ptr(const Ptr& other) = default;
  22. Ptr& operator=(const Ptr& rhs) = default;
  23. auto operator*() const -> T& { return *ptr; }
  24. auto operator->() const -> T* { return ptr; }
  25. T* Get() const { return ptr; }
  26. private:
  27. T* ptr;
  28. };
  29. } // namespace Carbon
  30. #endif // EXECUTABLE_SEMANTICS_COMMON_PTR_H_