C++函数的四种传参方式

1、call-by-value

2、call-by-constant-reference

3、call-by-lvalue-reference   (call-by-reference)

4、call-by-rvalue-reference  (C++11)


1、call-by-value    小对象(复制代价小);不应该被函数改变

传值调用

int add(int a, int b)
{
	return a + b;
}


2、call-by-constant-reference: 大对象(复制代价大);不应该被函数改变

传常量引用调用

int find(const vector<int> & arr)
{
	...
	return item;
}


3、call-by-lvalue-reference:  所有可以被函数改变的对象

传左值引用调用(简称传引用调用)

double swap(double a, double b)
{
	...
}


4、call-by-rvalue-reference:  对于会被销毁的右值,用移动(move)代替复制(copy)

传右值引用调用

//重载
string returnLastItem(const vector<string> & arr);  //处理传入左值的情况
string returnLastItem(vector<string> && arr);       //处理传入右值的情况

vector<string> vec{ "hello", "world" };

cout << returnLastItem(vec) << endl; 
cout << returnLastItem({ "hello", "world" }) << endl;


【如有不当之处,请评论予以指正】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值