对象的返回有三种情况:
①按值返回
按值返回会产生临时变量。一般存储单一、c++的内置类型使用值传递。按值返回总是很安全的。
②按常量引用返回
引用返回不会产生临时变量,如果传递的是自定义类型(大的、复杂的对象),比如class,那么函数返回最好用引用传递,防止产生临时变量,增加内存的负担,可节省复制的开销。被传递的变量不会被改变。
下面这个例子只是告诉你怎么用常量引用返回,实际上这里用按值返回也很方便。
#include<iostream>
#include<vector>
using namespace std;
const int& findMax(const vector<int>& arr)
{
int maxIndex = 0;
for (int i=1;i<arr.size();i++)
{
if (arr[i] > arr[maxIndex])
maxIndex = i;
}
return arr[maxIndex];
}
int main()
{
vector<int> test = {1,2,3,4,5,3,1};
int maxValue = findMax(test);
cout << "maxValue=" << maxValue << endl;
return 0;
}
③引址返回
引用返回不会产生临时变量,被传递的变量不会被改变。