C++引进了引用的概念,引用是一个对象的别名。下面讲讲为什么要尽量使用引用传参
1.方便
看看下面的C语言实现的交换的错误代码
#include <stdio.h>
#include <stdlib.h>
void swap(int _left, int _right) {
int temp = _left;
_left = _right;
_right = temp;
}
int main() {
int a = 10;
int b = 20;
swap(a, b);
printf("%d\r\n%d", a, b);
return 0;
}
当你调用这个函数时,你并不会得到希望的结果。
输出结果:
10
20
更改代码
#include <stdio.h>
#include <stdlib.h>
void swap(int* _left, int *_right) {
int temp = *_left;
*_left = *_right;
*_right = temp;
}
int main() {
int a = 10;
int b = 20;
swap(&a, &b);
printf("%d\r\n%d", a, b);
return 0;
}
输出:
20
10
这个结果是我们需要的,两个变量的值成功交换了,第一段代码错误的原因是什么?在调用swap函数时,a,b被拷贝了一份,在函数体里面,对a,b的操作实际上是对a,b副本的操作。
第二种方法虽然达到了目的,但是总有麻烦和不美观。
使用C++,用引用传递参数
#include <iostream>
void swap(int& _left, int& _right) {
int temp = _left;
_left = _right;
_right = temp;
}
int main() {
int a = 10;
int b = 20;
swap(a, b);
std::cout << a << std::endl << b << std::endl;
return 0;
}
输出结果:
20
10
可以看到,swap函数只被改动了很小的一部分,但是结果有所不同,因为当a,b传入swap函数时,a,b没有被拷贝,在函数体内对a,b的操作就是对它们本身进行操作。
下面提供了一种swap函数的版本
void swap(int& _left, int& _right) {
int temp = std::move(_left);
_left = std::move(_right);
_right = std::move(temp);
}
这是标准库实现swap的方法,通过右值引用减少不必要的内存大小
2.节约
第一个标题最后一段提到了使用引用能够减少不必要的内存大小。下面具体讲讲原因。
#include <iostream>
class Student {
public:
Student(int _id = 0)
: id_(_id) {
std::cout << "Student()" << std::endl;
}
Student(Student& other)
: id_(other.id_) {
std::cout << "Student(Student&)" << std::endl;
}
Student(Student&& other)
: id_(other.id_) {
std::cout << "Student(Student&&)" << std::endl;
}
~Student() {
std::cout << "~Student()" << std::endl;
}
int id() {
return id_;
}
private:
int id_;
};
void printId(Student s) {
std::cout << s.id() << std::endl;
}
int main() {
Student s;
printId(s);
return 0;
}
输出结果
Student()
Student(Student&)
0
~Student()
~Student()
在main函数中只有一个Student对象,为什么被析构了两次?
再看看输出,有一个Student(Student&),看来s是被拷贝过一份的,但是我们并不需要这种拷贝,拷贝了有什么效果吗,显然在这个程序中没有,所以我们应该使用引用传递参数而不是值传递参数
void printId(Student& s) {
std::cout << s.id() << std::endl;
}
拷贝的问题解决
C++ 引用提供了一种对象的别名,使用引用传参可以避免值传递时的对象拷贝,提高效率。文章通过对比C语言的值传递和C++的引用传递,展示了引用在交换变量值时的正确性和简洁性,并通过实例说明引用能减少不必要的内存开销,防止无用的拷贝导致的额外资源消耗。
15万+

被折叠的 条评论
为什么被折叠?



