首页 > 编程语言 > 详细

c++ new 的简单使用

时间:2021-03-08 16:09:03      阅读:20      评论:0      收藏:0      [点我收藏+]

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

 

c++ new 的简单使用

原文:https://www.cnblogs.com/sau-autumnwind/p/14499952.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!