cpp_obj_par_ret - ShenYj/ShenYj.github.io GitHub Wiki
使用对象类型作为函数的参数或者返回值,可能会产生一些不必要的中间对象
- 作为参数
class Car {
public:
Car() {
cout << "Car() - " << this << endl;
}
Car(const Car &car) {
cout << "Car(const Car &) - " << this << endl;
}
void run() {
cout << "run()" << endl;
}
};
void test(Car car) {
}
int main() {
Car car; /// 创建 一个对象
test(car); /// 拷贝 一个对象
return 0;
}
避免发生拷贝: 对象类型作为参数时,推荐使用指针或者引用类型
class Car {
public:
Car() {
cout << "Car() - " << this << endl;
}
Car(const Car &car) {
cout << "Car(const Car &) - " << this << endl;
}
void run() {
cout << "run()" << endl;
}
};
/// 参数改为引用类型
void test(Car &car) {
}
int main() {
Car car;
test(car);
return 0;
}
- 做为返回值
class Car {
public:
Car() {
cout << "Car() - " << this << endl;
}
Car(const Car &car) {
cout << "Car(const Car &) - " << this << endl;
}
void run() {
cout << "run()" << endl;
}
};
Car test() {
Car car; /// 创建 一个对象
return car; /// 创建的 car 在当前 test函数栈空间内,需要 return 到 main 函数使用, 而 car 的生命周期仅限于 test 函数栈空间
}
int main() {
/// 写法一 创建三次对象: 两次普通构造、一次拷贝构造
Car car; /// 创建 一个对象
car = test(); /// 提前将 test 函数中创建的 car对象拷贝构造到 main 函数
/// 写法二 创建两次对象: 一次普通构造、一次拷贝构造
Car car1 = test();
return 0;
}