Symbian Developer Library

SYMBIAN OS V6.1 EDITION FOR C++

[Index] [Glossary] [Previous] [Next]



How to clean up non-CBase classes


Cleanup for a 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();

[Top]


Cleanup support for an R class

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();
 }
 


Notes