A. 尽量使用基类做为参数;
B. 使用 const TDesC& 当不要修改时,使用引用当要修改时,使用TDes&
C.从HBufC到TDes
HBufC* CPoem::DoGetLineL(TInt aLineNumber)
{// Code omitted for clarity. Allocates and returns a heap buffer
// containing the text of aLineNumber (leaves if aLineNumber is out of range)
}
void CPoem::GetLineL(TInt aLineNumber, TDes& aDes)
{
HBufC* line = DoGetLineL(aLineNumber);
CleanupStack::PushL(line);
// Is the descriptor large enough (4 bytes or more) to return an
// integer representing the length of data required?
if (aDes.MaxLength() < line->Length())
{
if (aDes.MaxLength() >= sizeof(TInt))
{// Writes the length required (TPckg is described later)
TPckg<TInt> length(line->Length());
aDes.Copy(length);
}
// Leave & indicate that the current length is too short
User::Leave(KErrOverflow); // Leaves are described in Chapter 2
}
else
{
aDes.Copy(*line);
CleanupStack::PopAndDestroy(line);
}
}
D.和 Stream 的数据交互
使用函数的方法:
// Writes the contents of iHeapBuffer to a writable stream
void CSampleClass::ExternalizeL(RWriteStream& aStream) const
{
// Write the descriptor’s length
aStream.WriteUint32L(iHeapBuffer->Length());
// Write the descriptor’s data
aStream.WriteL(*iHeapBuffer, iHeapBuffer->Length());
}
// Instantiates iHeapBuffer by reading the contents of the stream
void CSomeClass::InternalizeL(RReadStream& aStream)
{
TInt size=aStream.ReadUint32L(); // Read the descriptor’s length
iHeapBuffer = HBufC::NewL(size); // Allocate iHeapBuffer
// Create a modifiable descriptor over iHeapBuffer
TPtr ptr(iHeapBuffer->Des());
// Read the descriptor data into iHeapBuffer
aStream.ReadL(ptr,size);
}
直接使用 << 和 >>
class TSomeClass
{
... // Omitted for clarity
private:
TBuf<12> iBuffer;
...
};
void TSomeClass::ExternalizeL(RWriteStream& aStream)
{
aStream << iBuffer;
...
}
void TSomeClass::InternalizeL(RReadStream& aStream)
{
aStream >> iBuffer;
...
}
D.TFileName 的使用
定义
const TInt KMaxFileName=0x100; // = 256 (decimal)
typedef TBuf<KMaxFileName> TFileName;
使用一个TFileName可能会产生500+字节的开销,所以应该尽量不要在栈上使用;
使用 TParse, TParsePtr, TParsePtrC
E.其它实用类
TLex: 用来进行数据类型转换和字符串解析
TPckg<T>: 可以对一个对像进行包装, 当相 C++ 的智能指针一样,对这个对象中的内容改变会影响到对象本身;
TPckgC<T>: 和TPckg相比,不能修包装的对象;调用会引起编译错误;
TPckgBuf<T>: 和TPckg相比,会创建一个对象的拷贝,修改不会改变原对象.
参照下图