实验1
#include <iostream>
using namespace std;
class test
{
//其他代码
test(){
cout << "//刚开始"<<endl;
}
~test()
{
cout << "//这里什么都不做,空的!"<<endl;
}
};
int main()
{
//然后这样
test *a = new test;
a->~test();//请问这句话到底会做什么?
}
点评:class默认是private,故上述程序编译不过
实验2:
修改为如下:
#include <iostream>
using namespace std;
class test
{
public:
//其他代码
test(){
cout << "//刚开始"<<endl;
}
test(int i){
cout << "//新的开始"<<endl;
}
~test()
{
cout << "//这里什么都不做,空的!"<<endl;
}
};
int main()
{
//然后这样
test *a = new test;
a->~test();//请问这句话到底会做什么?
test t_a;
t_a.test();
t_a.test(1);
t_a.~test();
t_a.~test();
}
点评:编译不过,不管定义了多少个形式的,构造函数只能调用一次(具体是哪个构造函数取决于你的定义对象时的形式)。运行结果如下:
$g++ -o main *.cpp
main.cpp: In function ‘int main()’:
main.cpp:26:5: error: invalid use of ‘test::test’
t_a.test();
^~~~
main.cpp:27:5: error: invalid use of ‘test::test’
t_a.test(1);
实验3
#include <iostream>
using namespace std;
class test
{
public:
//其他代码
test(){
cout << "//刚开始"<<endl;
}
test(int i){
cout << "//新的开始"<<endl;
}
~test()
{
cout << "//这里什么都不做,空的!"<<endl;
}
};
int main()
{
//然后这样
test *a = new test;
a->~test();//请问这句话到底会做什么?
test t_a;
t_a.~test();
t_a.~test();
}
点评: 定义的对象最后还会有析构函数;new的对象不会。运行结果如下:
g++−omain∗.cppg++−omain∗.cppmain
//刚开始
//这里什么都不做,空的!
//刚开始
//这里什么都不做,空的!
//这里什么都不做,空的!
//这里什么都不做,空的!
实验4
---
int main()
{
//然后这样
test *a = new test;
a->~test();//请问这句话到底会做什么?
a->~test();
delete a;
a=NULL;
cout << a << endl;
a->~test();
system("pause");
return 0;
}

总结:
构造函数不能够多次调用;析构函数随你调用多次都行;如果是定义了对象,最后还会执行系统会自动执行析构函数(vs上亲测)。如果是new一个类,则不会。需要delete,否则内存泄漏。delete会调用析构函数。有趣的是当指向test类的指针为空时,仍然能访问析构函数。
本文深入探讨C++中析构函数的行为,包括其调用时机与次数,特别是在对象销毁过程中的作用。通过实验对比,解析new与直接定义对象在析构函数调用上的区别,以及内存管理的重要性。

被折叠的 条评论
为什么被折叠?



