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.

delete iObject6;<br />

}<br />

We didn't use the cleanup stack here because iObject6 is a member variable. The<br />

important thing about the code above is that nothing can leave between the<br />

CleanupStack::Pop(), and the assignment of the CZ* to iObject6.<br />

If we want to refer to the new CZ from an automatic variable, then we need the cleanup stack<br />

throughout the lifetime of the CZ. We could use the NewL() above and then push the object<br />

to the cleanup stack on return, but that would be wasteful. Instead, we use a static<br />

NewLC()function that operates like NewL() but doesn't pop the object from the cleanup<br />

stack before returning:<br />

CZ* CZ::NewLC()<br />

{<br />

CZ* self = new(ELeave) CZ;<br />

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

self->ConstructL();<br />

return self;<br />

}<br />

This allocates the new CZ and, if all goes well, leaves it on the cleanup stack – that's what<br />

the C in NewLC() stands for. If anything fails, the function leaves and everything is cleaned<br />

up.<br />

This is used from Use 7, whose handler is<br />

case EMagicCmdUse7:<br />

{<br />

CZ* z = CZ::NewLC();<br />

z->iX->UseL();<br />

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

}<br />

This is very convenient, but it's not necessary to use NewL() and NewLC() in every class. If<br />

your class is a one-off class, designed for use only in your application, then it's a waste to<br />

code NewL()-type functions, and it's easy enough to code new followed by ConstructL()<br />

in the one place where your application constructs an instance of this class. For classes<br />

designed for frequent reuse, the case for encapsulating construction in NewL()-type<br />

functions is more compelling.<br />

For classes with more than one C++ constructor such as application documents that may<br />

construct either a blank document, or a document loaded in from file, there is a very strong<br />

case to wrap up the various construction sequences in distinct NewL()-type functions.<br />

During development, you sometimes change your mind about things like this and equip a<br />

class with NewL()-type functions, or occasionally even remove them. The presence or<br />

absence of these convenience functions is not a fundamental property of a class, which is<br />

probably why it's not reflected in a naming convention.

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

Saved successfully!

Ooh no, something went wrong!