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.

  • 相关阅读:
    如何编写 maptalks plugin
    maptalks 如何加载 ArcGIS 瓦片图层
    vue 地图可视化 maptalks 篇
    个人博客如何开启 https
    vue.js多页面开发环境搭建
    vue 自动化部署 jenkins 篇
    virtualbox ubuntu 安装 openssh-server
    从零开始学 Spring Boot
    数据结构
    vue 转换信息为二进制 并实现下载
  • 原文地址:https://www.cnblogs.com/larry-xia/p/10263859.html
Copyright © 2011-2022 走看看