non_null_ptr.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #pragma once
  2. #include <library/cpp/yt/misc/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 TMutablePtr = TNonNullPtr<std::remove_const_t<T>>;
  42. using TNonNullPtrBase<T>::TNonNullPtrBase;
  43. friend TNonNullPtr<T> GetPtr<T>(T& ref) noexcept;
  44. public:
  45. TNonNullPtr(TMutablePtr 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_