non_null_ptr.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #pragma once
  2. #include "concepts.h"
  3. namespace NYT {
  4. ////////////////////////////////////////////////////////////////////////////////
  5. // We have one really strange rule in our codestyle - mutable arguments are passed by pointer.
  6. // But if you are not a fan of making your life indefinite,
  7. // you can use this helper, that will validate that pointer you pass is not null.
  8. template <class T>
  9. class TNonNullPtr;
  10. template <class T>
  11. class TNonNullPtrBase
  12. {
  13. public:
  14. TNonNullPtrBase(T* ptr) noexcept;
  15. TNonNullPtrBase(const TNonNullPtrBase& other) = default;
  16. TNonNullPtrBase(std::nullptr_t) = delete;
  17. TNonNullPtrBase operator=(const TNonNullPtrBase&) = delete;
  18. T* operator->() const noexcept;
  19. T& operator*() const noexcept;
  20. protected:
  21. T* Ptr_;
  22. TNonNullPtrBase() noexcept;
  23. };
  24. template <class T>
  25. TNonNullPtr<T> GetPtr(T& ref) noexcept;
  26. template <class T>
  27. class TNonNullPtr
  28. : public TNonNullPtrBase<T>
  29. {
  30. using TConstPtr = TNonNullPtr<const T>;
  31. friend TConstPtr;
  32. using TNonNullPtrBase<T>::TNonNullPtrBase;
  33. friend TNonNullPtr<T> GetPtr<T>(T& ref) noexcept;
  34. };
  35. // NB(pogorelov): Method definitions placed in .h file (instead of -inl.h) because of clang16 bug.
  36. // TODO(pogorelov): Move method definitions to helpers-inl.h when new clang will be used.
  37. template <CConst T>
  38. class TNonNullPtr<T>
  39. : public TNonNullPtrBase<T>
  40. {
  41. using TMutPtr = TNonNullPtr<std::remove_const_t<T>>;
  42. using TNonNullPtrBase<T>::TNonNullPtrBase;
  43. friend TNonNullPtr<T> GetPtr<T>(T& ref) noexcept;
  44. public:
  45. TNonNullPtr(TMutPtr mutPtr) noexcept
  46. : TNonNullPtrBase<T>()
  47. {
  48. TNonNullPtrBase<T>::Ptr_ = mutPtr.Ptr_;
  49. }
  50. };
  51. ////////////////////////////////////////////////////////////////////////////////
  52. } // namespace NYT
  53. #define NON_NULL_PTR_H_
  54. #include "non_null_ptr-inl.h"
  55. #undef NON_NULL_PTR_H_