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:
A similar function, which leaves the created descriptor on the cleanup stack for the caller, would be coded as follows:
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:
You must return an HBufC* as follows:
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.
HBufC* CreateSomeDescriptorL()
{
_LIT(KBert, "bert");
HBufC* newBert = KBert().AllocL();
return (newBert);
}
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
else
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);
}
Comments:
<< Home
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?
Post a Comment
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?
<< Home