C++函数返回值传递

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.

posted @ 2019-01-13 20:26  summer91  阅读(3584)  评论(0编辑  收藏  举报