RefCountedObject.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // RefCountedObject.h
  3. //
  4. // Library: Foundation
  5. // Package: Core
  6. // Module: RefCountedObject
  7. //
  8. // Definition of the RefCountedObject class.
  9. //
  10. // Copyright (c) 2004-2009, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // SPDX-License-Identifier: BSL-1.0
  14. //
  15. #ifndef Foundation_RefCountedObject_INCLUDED
  16. #define Foundation_RefCountedObject_INCLUDED
  17. #include "Poco/Foundation.h"
  18. #include "Poco/AtomicCounter.h"
  19. namespace Poco {
  20. class Foundation_API RefCountedObject
  21. /// A base class for objects that employ
  22. /// reference counting based garbage collection.
  23. ///
  24. /// Reference-counted objects inhibit construction
  25. /// by copying and assignment.
  26. {
  27. public:
  28. RefCountedObject();
  29. /// Creates the RefCountedObject.
  30. /// The initial reference count is one.
  31. void duplicate() const;
  32. /// Increments the object's reference count.
  33. void release() const throw();
  34. /// Decrements the object's reference count
  35. /// and deletes the object if the count
  36. /// reaches zero.
  37. int referenceCount() const;
  38. /// Returns the reference count.
  39. protected:
  40. virtual ~RefCountedObject();
  41. /// Destroys the RefCountedObject.
  42. private:
  43. RefCountedObject(const RefCountedObject&);
  44. RefCountedObject& operator = (const RefCountedObject&);
  45. mutable AtomicCounter _counter;
  46. };
  47. //
  48. // inlines
  49. //
  50. inline int RefCountedObject::referenceCount() const
  51. {
  52. return _counter.value();
  53. }
  54. inline void RefCountedObject::duplicate() const
  55. {
  56. ++_counter;
  57. }
  58. inline void RefCountedObject::release() const throw()
  59. {
  60. try
  61. {
  62. if (--_counter == 0) delete this;
  63. }
  64. catch (...)
  65. {
  66. poco_unexpected();
  67. }
  68. }
  69. } // namespace Poco
  70. #endif // Foundation_RefCountedObject_INCLUDED