CleanupStack - Symbian’s partial answer to garbage collection.
Posted by kiran on April 8, 2008
Resources are always scarce, aren’t they? I have always wanted someone to take care of the resources I need and use. For instance that book I had borrowed from a friend with a promise of returning in 2 days time. Which despite all my good intentions I still forget to return even after 3 weeks have lapsed. In real life it is still a dream, but in my Symbian life I have found someone - “Cleanup Stack”.
Cleanup stack is a place to store the variables which are not member variables of any class but allocated on Heap (defined inside function). The objects are pushed onto CleanupStack once they are allocated memory. And popped from the CleanupStack after we are done with them. In between if any exception occurs (We call it a “Leave” in Symbian ), the CleanupStack Pops the object and calls the destructor of the object.
Few questions are always popped up when we talk about CleanupStack. Lets try to find the answers for some of them.
Q. What are the different types of Objects that we can push on CleanupStack?
A. CleanupStack has three overloaded Push functions.
-
1) PushL(TAny* aObj): We can put any object (void* in C++)
-
2) PushL(CBase* aObj): We can put a CBase class object. So it is advised in Symbian to derive your class from CBase. To use the CleanupStack functionalities.
-
3) PushL(TCleanupItem aItem): TCleanupItem encapsulates the cleanup operation (function pointer) and an Object with it. That function is called if any Leave occurs.
Q. How to Use CleanupStack to handle the object of a non CBase class?
A. We should use TCleanupItem to put the object on CleanupStack of non CBase classes. Using TCleanupItem we can associate an Object with a function which will be called if a Leave occurs.
Q. What will happen if we put non CBase object on CleanupStack?
A. CleanupStack will call User::Free() for the object. But will not call the destructor. If the pushed object contains data, it’s a memory leak.
Q. What if I forget to pop the items from CleanupStack?
A. We get E32User CBase 71 Panic. You must pop an item before you leave a function.
Q. Suppose I have pushed 100 items onto CleanupStack, do I have to pop all of them manually?
A. Not actually. One of the overloaded PopAndDestroy function takes the count which is number of items to be popped and destroyed.
eg. PopAndDestroy(100);
Lastly, don’t use the “Check” function as it is for debug builds used by Symbian. It can crash your application if not used properly.
