打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
c++ new 的简单使用
userphoto

2022.11.06 北京

关注

new 和 delete

c++ 的 new 和 delete 与 c的 malloc 和 free 区别之一是:

调用 new  和 delete 时会调用类的构造函数和析构函数

上代码

#include <iostream>

using namespace std;


class student
{
private:
        int age;
public:
        student(int a);
        ~student();
};
//构造函数
student::student(int a)
{
        age = a;
        cout << "student" << endl;
}
//析构函数
student::~student()
{
        cout << "~student" << endl;
}

int main()
{
        student *a = new student(2);
        //delete a;
        return 0;
}

输出

student

因为没有调用 delete a,所以只有构造函数被调用了。

加上 delete a

输出

student
~student

可知,在调用 delete 时 才会调用类的析构函数

如果不调用delete *a 上的空间就会泄漏

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
【转】常见的内存错误以及如何避免
编码中常见的4类内存管理错误
C 类和对象
sql 触发器
C语言《学生成绩管理系统》
oracel存储过程
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服