03.01.2013 Views

Chapter 1

Chapter 1

Chapter 1

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CleanupStack::PushL(x);<br />

x->UseL();<br />

CleanupStack::PopAndDestroy(x);<br />

}<br />

The cleanup stack class, CleanupStack, is defined in e32base.h. With these changes in<br />

place, here's what happens:<br />

� Immediately after we have allocated the CX and stored its pointer in x, we also push a<br />

copy of this pointer to the cleanup stack.<br />

� We then call UseL().<br />

� If this doesn't fail, our code pops the pointer from the cleanup stack and deletes the<br />

object. We could have used two lines of code for this (CleanupStack::Pop(),<br />

followed by delete x), but this is such a common pattern that the cleanup stack<br />

provides a single function to do both.<br />

� If UseL() does fail, then as part of leave processing, all objects on the cleanup stack<br />

are popped and destroyed anyway.<br />

So our code works whether UseL() leaves or not. Change memorymagic to include this<br />

code, rebuild, set the heap to fail on the second allocation, invoke Use 3, and then exit the<br />

application. Once again, all will be well.<br />

Of course, we could have done this without the aid of the cleanup stack by using code like<br />

this:<br />

case EMagicCmdUse3:<br />

{<br />

CX* x = new(ELeave) CX;<br />

TRAPD(error, x->UseL()):<br />

if(error)<br />

{<br />

delete x:<br />

User::Leave(error);<br />

}<br />

delete x;<br />

}<br />

However, this is much less elegant. The cleanup stack works particularly well for a long<br />

sequence of operations, such as<br />

case EMagicCmdUse3:<br />

{<br />

CX* x = new(ELeave) CX;<br />

CleanupStack::PushL(x);<br />

x->UseL():<br />

x->UseL();<br />

x->UseL();<br />

CleanupStack::PopAndDestroy(x);<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!