为什么在这里调用析构函数两次



我不明白为什么第二个对象 d2 的析构函数被调用两次。我知道过去有人问过这类问题,但每一个问题都与我的有一些相关的差异。任何帮助将不胜感激。谢谢。

#include <iostream>
using namespace std;
class data{
char s1[50];
static int j;
public:
    data(char s[50]){
        for(int i = 0; i < 50; i++){
            s1[i] = s[i];
        }
    }
    void show(){
        cout <<"Data " << ++j <<"=" << s1 << endl;
    }
    void compare(data d){
        for(int i = 0; i < 50; i++){
            if(d.s1[i] != s1[i]){
                cout << "Both Objects have different text." << endl;
                break;
            }
        }
    }
    ~data(){
        cout << "Release memory allocated to " << s1 << endl;
    }
};
int data::j;
int main(){
    char str[50],str1[50];
    cin>>str;
    cin>>str1;
    data d1(str);
    data d2(str1);
    d1.show();
    d2.show();
    d1.compare(d2);
    return 0;
}

此代码运行时的输出为:

 Data 1=object1
 Data 2=object2
 Both Objects have different text.
 Release memory allocated to object2
 Release memory allocated to object2
 Release memory allocated to object1    

因为您要按值而不是按引用将输入参数传递给compare

最新更新