Symbian Programming Summary-Fundamentals-Collections and Buffers (2)-Verifying rarray::append whether to save object copies
One, the verification stack object will automatically destroy
We know that in C + +, the Stack object is created in the function, and when the function exits, the stack object is automatically destroyed (the stack pointer moves back and the stack memory is overwritten). How do you verify this? We need to define a shape variable outside the function, get the address of the variable within the function, and revert the address to an object after the function call is complete:
TInt iAddr;
/**
* 将地址还原成描述符对象并显示出来
* @param aAddr 地址
*/
LOCAL_C void PrintString(TInt aAddr)
{
const TBufC<50>& str = *((TBuf<50>*)aAddr);
console->Write(str);
}
LOCAL_C void DoTest()
{
_LIT(KString, "Test String");
TBufC<50> str(KString);
// 获取栈对象str的地址:
iAddr = (TInt)&str;
PrintString(iAddr); // 此处可以正常显示出“Test String”
}
LOCAL_C void MainL()
{
DoTest();
PrintString(iAddr); // 此处显示乱码,证明栈对象会自动销毁
}
Test: The Rarray::append method saves a copy of the object
typedef TBufC<20> TFixedBufC;
RArray<TFixedBufC> iArr;
LOCAL_C void DoInsert()
{
TFixedBufC text1(_L("test1"));
iArr.Append(text1);
}
LOCAL_C void MainL()
{
DoInsert();
TFixedBufC& desc = iArr[0];
console->Write(desc);
}
Output results:
According to the 1th analysis, the Doinsert function of the stack object Text1 will be automatically destroyed when the Doinsert function returns, if the Rarray::append method is simply to save the Text1 reference, the program can not be the correct output test1. Therefore, we have proved through this experiment that a copy of the Text1 is constructed in the Append method.