为什么在这里调用析构函数两次
Why the destructor is being called twice here?
我不明白为什么第二个对象 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
。
相关文章:
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 为什么参数在构造 std::thread 时移动两次
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 调用一个小函数两次(例如在if条件和主体中)比将结果存储在局部变量中更可取
- 在钻石问题的求解中,为什么要虚拟地继承两次grand-parent类
- 为什么这个自定义分配器的析构函数在 GCC/MSVS 的 stdlib 中被调用两次
- "... already defined in *.obj"但我没有在同一范围内两次定义任何变量
- 在条件运算符中使用对象两次会产生 UB 吗?
- 程序在运行两次后关闭
- 在指定的响应之前C++用户输入两次
- QGraphicsScene项目在两次(x2)位置绘制
- 为什么我的串行串行在Arduino IDE上通过串行显示器进行两次打印
- 为什么在这里调用析构函数两次
- 为什么在这里对c++输入文件流进行两次检查
- 两次在c++中的差异
- C++ cout 打印两次在循环中做