zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    【技术博客】利用handler实现线程之间的消息传递
    BUAA软件工程个人作业-软件案例分析
    BUAA软件工程结对项目作业
    BUAA软件工程个人项目作业
    BUAA软件工程个人博客作业
    BUAA-软件工程第一次作业
    BUAA-OO-最后单元总结
    BUAA-OO-第三单元总结
    BUAA-OO-第二单元总结
    第四单元总结&&OO总结
  • 原文地址:https://www.cnblogs.com/larry-xia/p/10263859.html
Copyright © 2011-2022 走看看