所以这是代码:
由于某些原因,该代码的输出结果为:
#include <iostream>
using namespace std;
class C {
public:
C() {i = 6; cout << "A:" << i << endl;}
C(int i0) {i = i0; cout << "B:" << i << endl;}
~C() {cout << "C:" << i << endl;}
private:
int i;
};
int main(int argc, char* argv[]) {
cout << "X" << endl;
C *c = new C;
cout << "Y" << endl;
}
由于某些原因,该代码的输出结果为:
X
A:6
Y
不知何故,当您到达代码结尾时,析构函数(C:6)从未被调用。这是为什么呢?同时,此代码确实调用了析构函数:
#include <iostream>
using namespace std;
class C {
public:
C() {i = 0; cout << "A:" << i << endl;}
C(int i0) {i = i0; cout << "B:" << i << endl;}
~C() {cout << "C:" << i << endl;}
private:
int i;
};
int main(int argc, char* argv[]) {
cout << "X" << endl;
C c;
cout << "Y" << endl;
}
new
关键字创建的对象调用delete
方法(注意:并非总是如此,但对于大多数情况都适用)。 - Kevin W.new
。 - user2249683