ScopedPtr.hpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_SCOPEDPTR_HPP
  14. #define ZT_SCOPEDPTR_HPP
  15. #include "Constants.hpp"
  16. #include "TriviallyCopyable.hpp"
  17. namespace ZeroTier {
  18. /**
  19. * Simple scoped pointer
  20. *
  21. * This is used in the core to avoid requiring C++11 and because auto_ptr is weird.
  22. */
  23. template<typename T>
  24. class ScopedPtr : public TriviallyCopyable
  25. {
  26. public:
  27. explicit ZT_INLINE ScopedPtr(T *const p) noexcept : m_ptr(p) {}
  28. ZT_INLINE ~ScopedPtr() { delete m_ptr; }
  29. ZT_INLINE T *operator->() const noexcept { return m_ptr; }
  30. ZT_INLINE T &operator*() const noexcept { return *m_ptr; }
  31. ZT_INLINE T *ptr() const noexcept { return m_ptr; }
  32. ZT_INLINE void swap(const ScopedPtr &p) noexcept
  33. {
  34. T *const tmp = m_ptr;
  35. m_ptr = p.m_ptr;
  36. p.m_ptr = tmp;
  37. }
  38. explicit ZT_INLINE operator bool() const noexcept { return (m_ptr != (T *)0); }
  39. ZT_INLINE bool operator==(const ScopedPtr &p) const noexcept { return (m_ptr == p.m_ptr); }
  40. ZT_INLINE bool operator!=(const ScopedPtr &p) const noexcept { return (m_ptr != p.m_ptr); }
  41. ZT_INLINE bool operator==(T *const p) const noexcept { return (m_ptr == p); }
  42. ZT_INLINE bool operator!=(T *const p) const noexcept { return (m_ptr != p); }
  43. private:
  44. ZT_INLINE ScopedPtr() noexcept {}
  45. ZT_INLINE ScopedPtr(const ScopedPtr &p) noexcept : m_ptr(nullptr) {}
  46. ZT_INLINE ScopedPtr &operator=(const ScopedPtr &p) noexcept { return *this; }
  47. T *const m_ptr;
  48. };
  49. } // namespace ZeroTier
  50. namespace std {
  51. template<typename T>
  52. ZT_INLINE void swap(ZeroTier::ScopedPtr<T> &a,ZeroTier::ScopedPtr<T> &b) noexcept { a.swap(b); }
  53. }
  54. #endif