Monday, October 13, 2008

Don't mix "const TDesC&" and "TPtrC"

As TPtrC can be seen as a constant quasi reference to a descriptor. Don't mix it with the real reference type for descriptors TDesC&.

Attention wrong sample code:
const TDesC& GetDescriptor() const
{
_LIT(KDescriptor, "Hello");
TPtrC des(KDescriptor);
return des;
}

This is a programming error: "Returning a reference to a locale variable." Which results in a runtime error (panic).

Rule: Don't you ever return a TPtrC when your function returns a const TDesC&!

The problem here is, that often you don't see that des is a TPtrC! E.g. when GetDescriptor() calls another function which returns a TPtrC! So you have to be patient.

Solution: Your function has to return a copy of the TPtrC. And the prototype of the function looks like this:
TPtrC GetDescriptor() const;