Dispose Pattern

Dispose Pattern helps explicitly destroying an object when you don't know exactly know when it needs to be destroyed due to several Smart Pointers referring to that object.

If you want to apply Dispose Pattern to an object managed by smart class, you need to add ‘Status' as member variable of object. ‘Status' should mean the object is in useless state since it already has been destroyed. If ‘Status' is in ‘already destroyed state', then it should prompt an error if anything tries referring to it or let it perform properly if otherwise.

Here is the sample sourcecode for Dispose Pattern.

class A
{
// When it is true, it means this object is in disposed state.
bool m_disposed;
public:
A()
{
// The newly generated object is not in disposed state.
m_disposed = false;
}
~A()
{
Dispose();
}
void Dispose()
{
if(m_disposed == false)
{
// Perform operation related to the destroyed object.
// For example, close all file handles included in that objects.
...
m_disposed = true;
}
}
};
typedef Proud::RefCount<A> APtr;
void Foo()
{
APtr a(new A); // Create an object
APtr b = a; // Two Smart Pointer variables share the same object.
a->Dispose(); // Forcibly destroy the object.
// Now both a and b objects are in disposed state.
// So no approach should be made to the object that a and b are referring to.
...
}

For your note, Dispose Pattern is being used in Java, C#, or other programming lanugages that have Smart Pointer and Garbage Collector.