| 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 |  | 
| 16 |  | 
| 17 | #ifndef Foundation_RefCountedObject_INCLUDED | 
| 18 | #define Foundation_RefCountedObject_INCLUDED | 
| 19 |  | 
| 20 |  | 
| 21 | #include "Poco/Foundation.h" | 
| 22 | #include "Poco/AtomicCounter.h" | 
| 23 |  | 
| 24 |  | 
| 25 | namespace Poco { | 
| 26 |  | 
| 27 |  | 
| 28 | class Foundation_API RefCountedObject | 
| 29 | 	/// A base class for objects that employ | 
| 30 | 	/// reference counting based garbage collection. | 
| 31 | 	/// | 
| 32 | 	/// Reference-counted objects inhibit construction | 
| 33 | 	/// by copying and assignment. | 
| 34 | { | 
| 35 | public: | 
| 36 | 	RefCountedObject(); | 
| 37 | 		/// Creates the RefCountedObject. | 
| 38 | 		/// The initial reference count is one. | 
| 39 |  | 
| 40 | 	void duplicate() const; | 
| 41 | 		/// Increments the object's reference count. | 
| 42 | 		 | 
| 43 | 	void release() const throw(); | 
| 44 | 		/// Decrements the object's reference count | 
| 45 | 		/// and deletes the object if the count | 
| 46 | 		/// reaches zero. | 
| 47 | 		 | 
| 48 | 	int referenceCount() const; | 
| 49 | 		/// Returns the reference count. | 
| 50 |  | 
| 51 | protected: | 
| 52 | 	virtual ~RefCountedObject(); | 
| 53 | 		/// Destroys the RefCountedObject. | 
| 54 |  | 
| 55 | private: | 
| 56 | 	RefCountedObject(const RefCountedObject&); | 
| 57 | 	RefCountedObject& operator = (const RefCountedObject&); | 
| 58 |  | 
| 59 | 	mutable AtomicCounter _counter; | 
| 60 | }; | 
| 61 |  | 
| 62 |  | 
| 63 | // | 
| 64 | // inlines | 
| 65 | // | 
| 66 | inline int RefCountedObject::referenceCount() const | 
| 67 | { | 
| 68 | 	return _counter.value(); | 
| 69 | } | 
| 70 |  | 
| 71 |  | 
| 72 | inline void RefCountedObject::duplicate() const | 
| 73 | { | 
| 74 | 	++_counter; | 
| 75 | } | 
| 76 |  | 
| 77 |  | 
| 78 | inline void RefCountedObject::release() const throw() | 
| 79 | { | 
| 80 | 	try | 
| 81 | 	{ | 
| 82 | 		if (--_counter == 0) delete this; | 
| 83 | 	} | 
| 84 | 	catch (...) | 
| 85 | 	{ | 
| 86 | 		poco_unexpected(); | 
| 87 | 	} | 
| 88 | } | 
| 89 |  | 
| 90 |  | 
| 91 | } // namespace Poco | 
| 92 |  | 
| 93 |  | 
| 94 | #endif // Foundation_RefCountedObject_INCLUDED | 
| 95 |  |