Symbian基礎總結 -- 驗證RArray::Append是否保存對象副本

 原文出處: http://www.cnblogs.com/felixYeou/archive/2008/11/20/1337780.html

 

一、驗證棧對象會自動銷燬

我們知道,在C++中,在函數中創建了棧對象,函數退出時,該棧對象會自動銷燬(棧指針後移了,棧內存會被覆蓋)。如何驗證這一點?我們需要在函數外定義一個整形變量,在函數內將該函數內獲取了變量的地址,在函數調用完畢後,將地址還原成對象:

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);    // 此處顯示亂碼,證明棧對象會自動銷燬 
    }

 

二、試驗:RArray::Append方法會保存對象的副本

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

輸出結果:

image

按照第一點分析,DoInsert函數內的棧對象text1會在DoInsert函數返回的時候被自動銷燬,如果RArray::Append方法只是簡單的保存了text1的引用的話,程序不可能能夠正確的輸出test1。所以,我們通過此試驗證明Append方法中構建了一個text1的副本。

 

三、證明:RArray::Append方法會保存對象的副本

typedef TBufC<20> TFixedBufC; 
RArray<TFixedBufC> iArr;

LOCAL_C void DoInsert() 
    { 
    TFixedBufC text1(_L("test1")); 
    TBuf<50> addrStr;


    // 獲取text1的地址 
    addrStr.AppendNum((TInt)&text1); 
    iArr.Append(addrStr); 
    console->Write(addrStr); 
    console->Write(_L("/n")); 
    }

LOCAL_C void MainL() 
    { 
    DoInsert(); 
    TFixedBufC& desc = iArr[0]; 
    TBuf<50> addrStr;


    // 獲取desc的地址 
    addrStr.AppendNum((TInt)&desc); 
    console->Write(addrStr); 
    }

image

我在函數DoInsert內獲取了描述符text1的地址並顯示,並將描述符text1使用RArray::Append方法添加到了集合內,在MainL方法內獲取了集合第一個元素的引用並將該引用的地址輸出。大家可以看到,輸出的兩個地址並不相同,從而證明了RArray::Append方法創建了對象的副本並保存。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章