C++ 按引用传递参数的好处

pass by reference

  • 对于数组和结构这种大的数据,按值传递(pass by value)需要创建副本,占内存费时间,使用引用就只传地址,和按指针传递一样,但是使用起来又比指针简单安全,就是在使用原数据。
  • 对于unique_ptr智能指针模板类,它只允许源指针是临时右值时候的赋值,所以如果实参不是临时右值,按值传递就会成为非法赋值,编译器报错。示例:
#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <algorithm> //for_each函数
using std::string;
using std::cout;
using std::cin;
using std::endl;
std::unique_ptr<int> make_int(int n)
{
	return std::unique_ptr<int> (new int(n));//返回int的智能指针,用传入的参数n初始化
}
void show(std::unique_ptr<int>  & a)//这里必须按引用传递,因为如果按值传递
//那么就要用一个非临时右值作为a的实参,对于unique_ptr类是不允许的
{
	cout << *a << ' ';
}
int main()
{
	int size = 5;
	std::vector<std::unique_ptr<int>> vp(size);
	for (int i=0;i<size;++i)
		vp[i] = make_int(rand() % 1000);
	vp.push_back(make_int(rand() % 1000));//可以调用成功是因为参数是一个临时右值
	for_each(vp.begin(), vp.end(), show);
	return 0;
}
41 467 334 500 169 724
Process returned 0 (0x0)   execution time : 0.329 s
Press any key to continue.
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值