What about this :
// Unknown.hppclass Unknown{private: int m_RefCount; inline Unknown() : m_RefCount(0) {} // Private constructor virtual ~Unknown() {} // Private destructorprotected: virtual selfDestroy() = 0;public: inline void grab() { ++m_RefCount; } inline void drop() { if(--m_RefCount <= 0) selfDestroy(); } inline int getRefCount() const { return m_RefCount; } template<class> friend class UnknownBase; // Whatever the syntax for this is};template<class T>class UnknownBase : virtual public Unknown{protected: inline UnknownBase() {} // Protected constructor virtual ~UnknownBase() {} // Protected destructorpublic: static T * Create();};
And then :
// Derived.hppclass Derived : public UnknownBase<Derived>{protected: virtual void selfDestroy();};// Derived.cppDerived * UnknownBase<Derived>::Create() { return new Derived(); }void Derived::selfDestroy() { delete this; }
This solves the problems of :
- Mandatory allocation via a common static function (must derive from UnknownBase because Unknown's constructor is private)
- Deallocation via a virtual function
- Reference counting in base class
- Mandatory virtual inheritance from Unknown because of mandatory inheritance from UnknownBase
Is there any problem with this approach?
[Edited by - Trillian on May 12, 2007 7:04:26 AM]