c++ 构造函数 析构函数 实验探究https://mp.youkuaiyun.com/postedit

本文深入探讨C++中析构函数的行为,包括其调用时机与次数,特别是在对象销毁过程中的作用。通过实验对比,解析new与直接定义对象在析构函数调用上的区别,以及内存管理的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实验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类的指针为空时,仍然能访问析构函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值