分享

c++ new 的简单使用

 悦光阴 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 上的空间就会泄漏

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多