Monday, May 09, 2005

 

Tip 5: Need to modify an HBufC? Call Des().

An HBufC is derived from TDesC, and inherits non-modifiable descriptor functionality. Because it is not derived from TDes, it isn’t modifiable. So to write into it, you have to create a modifiable descriptor over the data area. This is done by calling HBufC::Des() which returns a TPtr and thus gives you access to all the modification functions such as Format(), Append() and Fill():

HBufC* robert = HBufC::NewL(4); // Read Only Bert
TPtr rwbert(robert->Des()); // Read Write Bert

_LIT(KBert, "Bert");

rwbert.Copy(KBert); // The data area of robert now contains Bert


Remember that that there must be space in the HBufC for the required change because descriptors don’t resize themselves automatically. If there isn’t, it will still compile - but you’ll get a panic at runtime, as described in Tip 2. This code will fail:

HBufC* robert = HBufC::NewL(2); // Read Only Bert
TPtr rwbert(robert->Des()); // Read Write Bert

_LIT(KBert, "Bert");

rwbert.Copy(KBert); // Panic! Not enough memory allocated to hold "Bert"


The reason why there is no HBuf class is discussed here.

Comments:
'bert' should be 'robert' non ?

if that is the case then :

'TPtrC rwrobert' should be a 'TPtr rwrobert' in order to allow the 'Copy' operation.

Also, instead of 'robert->Des()' one can simply dereference the 'HBufC* robert' and simply do '*robert'.
 
You're right.

(1) I've corrected the typo which used bert instead of robert.

(2) I've also changed the TPtr used to access the descriptor data, from TPtrC (which is non-modifiable) to TPtr (which is modifiable, and can thus be used to call Copy() - defined by TDes, not TDesC.

(3) I've not corrected the call to robert->Des() to a pointer dereference because that returns a constant descriptor and you can't create a TPtr from a TDesC. The subject of this post is that you indeed have to call Des() when you need modifiable access to the data area of an HBufC. Just don't call it when you only need non-modifiable access (as in Tip 6).
 
Post a Comment

<< Home

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

Google
WWW Top Tips for Descriptors