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.

  • 相关阅读:
    Nacos微服务部署(超详细)基于Centos7
    Centos7配置Mysql5.7数据库
    django搭建web (一)
    NetFPGA-1G-CML Demo --- reference_router_nf1_cml
    Linux下Java通用安装方法
    NetFPGA-1G-CML Demo --- openflow_switch
    原型设计(结对第一次)
    第二次作业——个人项目实战
    游戏
    python学习笔记-问题
  • 原文地址:https://www.cnblogs.com/larry-xia/p/10263859.html
Copyright © 2011-2022 走看看