RefCounted.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #pragma once
  16. class RefCounted;
  17. inline void intrusive_ptr_add_ref(RefCounted *ptr);
  18. inline void intrusive_ptr_release(RefCounted *ptr);
  19. /**
  20. * Provides a base implementation of reference counting.
  21. *
  22. * To be used with boost::intrusive_ptr.
  23. */
  24. class RefCounted{
  25. protected:
  26. RefCounted(): ref_count_(0){}
  27. virtual ~RefCounted(){}
  28. private:
  29. /**
  30. * Reference count used for boost::intrusive_ptr.
  31. */
  32. long ref_count_;
  33. friend void ::intrusive_ptr_add_ref(RefCounted *ptr);
  34. friend void ::intrusive_ptr_release(RefCounted *ptr);
  35. };
  36. /**
  37. * Add a reference to a pointer.
  38. *
  39. * @param ptr[in] Pointer to reference.
  40. */
  41. inline void intrusive_ptr_add_ref(RefCounted *ptr){++ (ptr->ref_count_);}
  42. /**
  43. * Remove a reference from a pointer.
  44. *
  45. * @param ptr[in] Pointer to de-reference.
  46. */
  47. inline void intrusive_ptr_release(RefCounted *ptr){
  48. if (-- (ptr->ref_count_) == 0) delete ptr;
  49. }