1. 程式人生 > >C++函數返回值傳遞

C++函數返回值傳遞

使用 spa 表達 turn index 有效 urn 但是 string

C++函數返回可以按值返回和按常量引用返回,偶爾也可以按引址返回。多數情況下不要使用引址返回。

使用按值返回總是很安全的,但是如果返回對象為類類型的,則更好的方法是按常量引用返回以節省復制開銷。必須確保返回語句中的表達式在函數返回時依然有效。

const string& findMax(const vector<string>& arr)
{
    int maxIndex = 0;
    for (int i=1;i<arr.size();i++)
    {
        if (arr[maxIndex] < arr[i])
            maxIndex 
= i; } return arr[maxIndex]; } const string& findMaxWrong(const vector<string>& arr) { string maxValue = arr[0]; for (int i=1;i<arr.size();i++) { if (maxValue < arr[i]) maxValue = arr[i]; } return maxValue; }

findMax()是正確的,arr[maxIndex]索引的vector是在函數外部的,且存在時間鯧魚調用返回的時間。

findMaxWrong()是錯誤的,maxValue為局部變量,在函數返回時就不復存在了。

C++函數返回值傳遞