【问题标题】:Why the destructor is being called twice here? [duplicate]为什么在这里调用了两次析构函数? [复制]
【发布时间】:2018-07-06 06:36:25
【问题描述】:

我不明白为什么第二个对象 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    

【问题讨论】:

  • 因为你是按值传递的。
  • 当您将d2 传递给d1.compare 时,它会进行复制,并且参数也会被破坏。
  • 我认为这是由于d1.compare(d2);,您通过值传递了d2,从而创建了data 类的新实例。
  • 您忘记添加日志以复制 ctor 和分配。
  • 我相信这与指定的副本不是同一个问题。不同之处在于另一个问题解决了复制构造函数的存在,在这个问题中它似乎被忽略了,因此另一个答案的答案在这里无效

标签: c++ class object constructor destructor


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 2012-04-23
    • 2013-10-01
    • 1970-01-01
    • 2021-11-06
    相关资源
    最近更新 更多