CBase classes TAny*Example code shown here demonstrates the use of cleanup for a
TAny*, in this case a TText.
TText* buffer=(TText*) User::Alloc(100*sizeof(TText));
// create a buffer
CleanupStack::PushL(buffer);
// push it to the cleanup stack: treated as TAny*
TPtr8 bufferPtr(buffer,100); // create a pointer to the buffer
...
// use the buffer
useBufferL(bufferPtr);
...
// destroy the buffer on the cleanup stack
CleanupStack::PopAndDestroy();
Example code shown here demonstrates how to provide cleanup stack
support for an R class. To do this, a TCleanupItem
object must be constructed with a pointer to the object to clean up, and a
pointer to a function that provides cleanup for that object. The most effective
way to do this is to define a TCleanupItem cast operator in the
class.
// TCleanupItem operator for objects of this class
TCleanupItem RExampleClass::operator TCleanupItem()
{
return TCleanupItem(Cleanup,this);
}
...
// cleanup function for use by cleanup stack
static void RExampleClass::Cleanup(TAny *aPtr)
{
// Invoke the Close member on the RExampleClass at aPtr
testConsole.Printf(_L("Doing cleanup.\n"));
((RExampleClass*)aPtr)->Close();
}
// Show use
void doExample()
{
RExampleClass r;
r.Open();
// Because RExampleClass has an operator TCleanupItem()
// pushing it is OK
CleanupStack::PushL(r);
// ...use r
// possibly some operations that leave
// PopAndDestroy() invokes RExampleClass::Cleanup()
CleanupStack::PopAndDestroy();
}
The operator returns a TCleanupItem object which
is constructed from a pointer to the static member function which performs the
class’s cleanup processing, and a pointer to the object to be cleaned
up.
Note that the static member function which provides the
class’s cleanup processing must cast the TAny* pointer into
a pointer of the class to be cleaned up to allow access to the class’s
member function to perform the cleanup
CleanupStack::PopAndDestroy() removes the item
from the stack and invokes the cleanup function set in the
TCleanupItem