c++ - 为什么赋值运算符重载会创建对象的副本?
问题描述
在下面给出的代码中,我cout
在所有类构造函数、析构函数和重载赋值运算符中都编写了语句。
#include <iostream>
using namespace std;
class person {
string name;
int age ;
int id ;
static int num;
public :
person (string name , int age) : name(name) , age(age) {
id = num++;
cout << "creating person : " << id << "(" << name <<")"<< endl;
}
person (const person &other) : name(other.name) , age(other.age) {
id = num++;
cout << "CREATING PERSON : " << id << "(" << name <<")" << " from : " << other.id << endl;
}
~person () {
cout << "killing person : " << id << "(" << name <<")" << endl;
}
const person operator= (const person &other) {
name = other.name ;
age = other.age;
//id = num++;
cout << "copying in : " << id << "(" << name <<")" << " from : " << other.id << endl;
return *this;
}
void print () {
cout << "name : " << name << ", age : " << age << ", id : " << id << endl;
}
int person::num = 1;
int main() {
person per1 ("p1" , 20);
person per2 ("p2" , 30);
person per3 ("p3" , 40);
cout << "see the strange object creation here: " << endl << endl;
per3 = per2 = per1;
return 0;
}
给定代码的输出结果是:
创建人:1(p1) 创建人:2(p2) 创建人:3(p3) 在这里看到奇怪的对象创建: 复制 : 2(p1) from : 1 *创造者:4(p1)来自:2* 复制 : 3(p1) from : 4 *创造者:5(p1)来自:3* 杀人者:5(p1) 杀人者:4(p1) 杀人者:3(p1) 杀人者:2(p1) 杀人者:1(p1)
我的问题是,是什么导致使用复制构造函数创建两个对象(4 和 5)?分配中使用的对象已经存在。有没有办法在不创建虚拟对象的情况下重载赋值运算符?这种方法似乎不是很优化。
解决方案
那是因为你operator=()
看起来像这样:
const person operator= (const person &other)
按价值返回。const
在这种情况下并没有真正的意义。
您实际上要做的是通过常量引用返回:
const person& operator= (const person &other)
那一个&
会让一切变得不同。
推荐阅读
- pandas - 如何将字符串转换为仅包含年份的日期?
- amazon-web-services - 如何在 AWS ElasticBeanStalk 中更新平台版本?
- reactjs - 了解 React 道具和事件
- java - 从非 CSV 数据为 Weka 生成 ARFF 文件
- django - 在 Django 、 gunicorn 和 nginx 中提供媒体文件
- go - GORM不输出相关数据
- recursion - F# 延续递归错误
- c# - 如何使用 AspNetCore.HealthChecks.SqlServer 检查多个数据库?
- mysql - 渴望加载多个和嵌套的关联
- python - Selenium Heroku:脚本正在运行,但仍收到 H10 错误