ptr.h 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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) : ptr(other.Get()) {}
  18. Ptr(std::nullptr_t) = delete;
  19. Ptr(const Ptr& other) = default;
  20. Ptr& operator=(const Ptr& rhs) = default;
  21. auto operator*() const -> T& { return *ptr; }
  22. auto operator->() const -> T* { return ptr; }
  23. T* Get() const { return ptr; }
  24. private:
  25. T* ptr;
  26. };
  27. } // namespace Carbon
  28. #endif // EXECUTABLE_SEMANTICS_COMMON_PTR_H_