C++中,malloc free 与 new delete的区别

文章目录


前言

随笔,记录一下malloc 与 new 的区别。

一、在C++中malloc 是什么?     

  • C++ 中的 malloc free 的问题:
    • (1) 程序员必须确定对象的长度
    • (2) malloc 返回一个 void 指针, C++ 不允许将 void 赋值给其他任何指针,必须强制
    • (3) malloc 可能申请内存失败,所以必须判断返回值来确保内存分配成功
    • (4) 用户在使用对象之前必须记住对他初始化,构造函数不能显示调用初始化(构造函数是由编译器调用的),用户有可能忘记调用初始化函数
    • 总结: C 的动态内存分配太复杂,容易令人混淆,是不可接受的

二、new

  • C++ 中推荐使用 new,delete
    • new 操作符能确定在调用构造函数初始化之前,所有不用显式确定调用是否成功
    • delete 表达式先调用析构函数,然后释放内存

三、例子

代码如下(示例):

#include <iostream>
extern "C"
{
    #include <stdio.h>
    #include <malloc.h>
    #include <string>
}

using namespace std;

class Student 
{
public:
    int id;
    string name;
};

int main(int argc, char const* argv[])
 {
    int size = 10;
    Student* st = (Student*)malloc(sizeof(Student) * size);
    
    Student* st2=new Student[10];


    for (Student* i = st; i < st + size; i++)
    {
        i->id = 123;
        //i->name = "qiumc";
    }
    (st+1)->id=999;
    st2->id=888;
    st2[1].id=777;

    cout << "st[0].id:" << st[0].id <<endl;
    cout << "st[1].id:" << st[1].id <<endl;
    cout << "st2.id:" << st2[0].id <<endl;
    cout << "st2[1].id:" << st2[1].id <<endl;
    
    free(st);
    // 如果要释放st内存,仅仅需要free(st);既可以,不能把st当做一个数组,进行逐个释放。
    delete []st2;
    return 0;
}

总结

        由以上代码可知,malloc与new都可以在c++中申请堆空间,不过要注意,malloc是函数,而new是一个操作符。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值