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;
【如有不当之处,请评论予以指正】