左值引用
左值引用
案例
swap 案例
看看下面的
#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;
}
这个结果是我们需要的,两个变量的值成功交换了,第一段代码错误的原因是什么?在调用
#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;
}
可以看到,
void swap(int& _left, int& _right) {
int temp = std::move(_left);
_left = std::move(_right);
_right = std::move(temp);
}
这是标准库实现
避免多次构造案例
#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()
**/
在
void printId(Student& s) {
std::cout << s.id() << std::endl;
}