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++ 程序更容易閱讀和維護。C++ 函數可以返回一個引用,方式與返回一個指針類似。
當函數返回一個引用時,則返回一個指向返回值的隱式指針。這樣,函數就可以放在賦值語句的左邊。
When a variable is returned by reference, a reference to the variable is passed back to the caller. The caller can then use this reference to continue modifying the variable, which can be useful at times. Return by reference is also fast, which can be useful when returning structs and classes.