c++官方文档-按值传递和按引用传递

#include<stdio.h>
#include<iostream>
#include<queue>
#include<map>
#include<memory.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <climits>
#include <sstream>
#include <cstdlib>
using namespace std;

/**
 * Calling a function with parameters taken by value causes copies of the values to be made.
 * This is a relatively inexpensive operation for fundamental types such as int,
 * but if the parameter is of a large compound type,
 * it may result on certain overhead.
 * For example, consider the following function:
 */
/**
 *调用传值函数的时候复制值到函数栈上,这个操作对于基本类型(like int)来说花费很少.
 *但是如果参数大的复合类型,花费就很大,比如下面这个函数.
 *函数的参数是俩个string(按值传递),返回的结果是俩个字符串拼接.
 *按值传递中,复制a和b的内容给函数,如果参数是长的字符串,这意味着调用函数时复制了大量的数据
 */
string concatenate(string a, string b)
{
    return a + b;
}
/**
 * 比较好的方式如下
 * 按引用传递不需要复制数据.函数操作直接在原始字符上(只是给它起了一个别名).
 *顶多这意味着给函数传递某些指针.
 *
 */
string concatenate2(string& a, string& b)
{
    return a + b;
}

/**
 * 按引用传递可能被调用的函数会修改引用的内容,我们可以这样解决
 */
string concatenate3(const string& a,const string& b)
{
    return a+b;
}
/**
 * that for most fundamental types,
 * there is no noticeable difference in efficiency, and in some cases,
 * const references may even be less efficient!
 *
 * 对于基本类型,效率并不会有多大差别,在某些情况下,常量引用可能效率更低
 */

/**
 * 参数的默认值
 */
int divide(int a,int b=2)
{
    int r;
    r = a/b;
    return (r);
}
int main(const int argc, char** argv)
{
    //from cstdlib
    cout<<divide(12)<<endl;
    cout<<divide(20,4)<<endl;
    return EXIT_SUCCESS;
}

 

posted on 2017-12-10 13:03 好吧,就是菜菜 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/shuiyonglewodezzzzz/p/8016649.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值