ScopedPtr.hpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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: 2025-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. {}
  29. ZT_INLINE ~ScopedPtr()
  30. { delete m_ptr; }
  31. ZT_INLINE T *operator->() const noexcept
  32. { return m_ptr; }
  33. ZT_INLINE T &operator*() const noexcept
  34. { return *m_ptr; }
  35. ZT_INLINE T *ptr() const noexcept
  36. { return m_ptr; }
  37. ZT_INLINE void swap(const ScopedPtr &p) noexcept
  38. {
  39. T *const tmp = m_ptr;
  40. m_ptr = p.m_ptr;
  41. p.m_ptr = tmp;
  42. }
  43. explicit ZT_INLINE operator bool() const noexcept
  44. { return (m_ptr != (T *)0); }
  45. ZT_INLINE bool operator==(const ScopedPtr &p) const noexcept
  46. { return (m_ptr == p.m_ptr); }
  47. ZT_INLINE bool operator!=(const ScopedPtr &p) const noexcept
  48. { return (m_ptr != p.m_ptr); }
  49. ZT_INLINE bool operator==(T *const p) const noexcept
  50. { return (m_ptr == p); }
  51. ZT_INLINE bool operator!=(T *const p) const noexcept
  52. { return (m_ptr != p); }
  53. private:
  54. ZT_INLINE ScopedPtr() noexcept
  55. {}
  56. ZT_INLINE ScopedPtr(const ScopedPtr &p) noexcept: m_ptr(nullptr)
  57. {}
  58. ZT_INLINE ScopedPtr &operator=(const ScopedPtr &p) noexcept
  59. { return *this; }
  60. T *const m_ptr;
  61. };
  62. } // namespace ZeroTier
  63. namespace std {
  64. template< typename T >
  65. ZT_INLINE void swap(ZeroTier::ScopedPtr< T > &a, ZeroTier::ScopedPtr< T > &b) noexcept
  66. { a.swap(b); }
  67. }
  68. #endif