RefCountedObject.h 1.7 KB

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