ScopedPtr.hpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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_ALWAYS_INLINE ScopedPtr(T *const p) noexcept : _p(p) {}
  28. ZT_ALWAYS_INLINE ~ScopedPtr() { delete _p; }
  29. ZT_ALWAYS_INLINE T *operator->() const noexcept { return _p; }
  30. ZT_ALWAYS_INLINE T &operator*() const noexcept { return *_p; }
  31. explicit ZT_ALWAYS_INLINE operator bool() const noexcept { return (_p != (T *)0); }
  32. ZT_ALWAYS_INLINE T *ptr() const noexcept { return _p; }
  33. ZT_ALWAYS_INLINE void swap(const ScopedPtr &p) noexcept
  34. {
  35. T *const tmp = _p;
  36. _p = p._p;
  37. p._p = tmp;
  38. }
  39. ZT_ALWAYS_INLINE bool operator==(const ScopedPtr &p) const noexcept { return (_p == p._p); }
  40. ZT_ALWAYS_INLINE bool operator!=(const ScopedPtr &p) const noexcept { return (_p != p._p); }
  41. ZT_ALWAYS_INLINE bool operator==(T *const p) const noexcept { return (_p == p); }
  42. ZT_ALWAYS_INLINE bool operator!=(T *const p) const noexcept { return (_p != p); }
  43. private:
  44. ZT_ALWAYS_INLINE ScopedPtr() noexcept {}
  45. ZT_ALWAYS_INLINE ScopedPtr(const ScopedPtr &p) noexcept : _p(nullptr) {}
  46. ZT_ALWAYS_INLINE ScopedPtr &operator=(const ScopedPtr &p) noexcept { return *this; }
  47. T *const _p;
  48. };
  49. } // namespace ZeroTier
  50. namespace std {
  51. template<typename T>
  52. ZT_ALWAYS_INLINE void swap(ZeroTier::ScopedPtr<T> &a,ZeroTier::ScopedPtr<T> &b) noexcept { a.swap(b); }
  53. }
  54. #endif