Saturday, August 02, 2008

When to return a TPtr or TPtrC?

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);

further reading

No comments:

stats counter