How to clean up non-CBase classes

Cleanup for a TAny*

This example code shows 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();  

Cleanup support for an R class

This example code shows 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
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"));
 (static_cast<RExampleClass*>(aPtr))->Close();
 }

// Show use
void DoTheExampleL()
 {
 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();
 }
 

Notes

  • 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.

  • 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. This allows the class member function to perform the cleanup

  • CleanupStack::PopAndDestroy() removes the item from the cleanupstack and invokes the cleanup function defined in the TCleanupItem object.

  • Remember that the TCleanupItem does not go onto the cleanupstack. the TCleanupItem is a container for the object that goes onto the cleanupstack. In this example, a pointer to the RExampleClass is put on the cleanupstack.