[英]Why does assignment operator overloading create a copy of an object?
在下面給出的代碼中,我在所有 class 構造函數、析構函數和重載賦值運算符中編寫了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;
}
給定代碼的 output 是:
creating person : 1(p1) creating person : 2(p2) creating person : 3(p3) see the strange object creation here: copying in : 2(p1) from : 1 *CREATING PERSON : 4(p1) from : 2* copying in : 3(p1) from : 4 *CREATING PERSON : 5(p1) from : 3* killing person : 5(p1) killing person : 4(p1) killing person : 3(p1) killing person : 2(p1) killing person : 1(p1)
我的問題是,是什么導致使用復制構造函數創建兩個對象(4 和 5)? 分配中使用的對象已經存在。 有沒有辦法在不創建虛擬對象的情況下重載賦值運算符? 這種方法似乎不是很優化。
那是因為您的operator=()
看起來像這樣:
const person operator= (const person &other)
按價值返回。 const
在這種情況下並沒有真正的意義。
您實際上要做的是通過常量引用返回:
const person& operator= (const person &other)
那一個&
將使一切變得不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.