Monday, May 09, 2005

10. How do I use heap descriptors as return types?

I want to create a new descriptor in my function. How do I return it to the caller?

You must return an HBufC* as follows:

HBufC* CreateSomeDescriptorL()
_LIT(KBert, "bert");
HBufC* newBert = KBert().AllocL();
return (newBert);
The calling function needs to know that it must take ownership of the returned heap-based descriptor and be responsible for deleting it when it has finished with it. Failure to do this is a common cause of memory leaks.

A similar function, which leaves the created descriptor on the cleanup stack for the caller, would be coded as follows:

HBufC* CreateSomeDescriptorLC()

_LIT(KBert, "bert");
HBufC* newBert = KBert().AllocLC();
return (newBert);

When should I return a TPtr or TPtrC? When shouldn't I?

TPtr or TPtrC are descriptors which do not own string data; they simply refer to data that exists in another descriptor. So you can use them to return a descriptor which references part of another descriptor argument, as long as its lifetime will not extend beyond that descriptor's lifetime. For example:

TPtrC LeftChar(const TDesC& aInput)

if (aInput.Length()>0)
return aInput.Left(1); // Returns the left-most character
return KNullDesC;

This, however, is not OK because stack-based fred will cease to exist when GetFred() returns:

TPtrC GetFred()
_LIT(KFred, "Fred");
TBufC<4> fred(KFred());
TPtrC fredPtr(fred);
return (fredPtr);

"return aInput.Length(1); // Returns the left-most character"

Typo: that should be aInput.Left(1);
Yes, you're right. Corrected.
I know it's an example but wouldn't

TPtrC LeftChar(const TDesC& aInput){
return aInput.Left(1); // Returns the left-most character or zero length TPtrC

do the same thing unless you're using ER5U?
The last example should be returning fredPtr instead of fred, right?
Yes, whoops! Corrected - thanks for pointing it out.
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?

WWW Descriptors FAQ