且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

malloc/free 与 new/delete 区别

更新时间:2022-09-15 16:53:15

malloc/free 是c++/c的标准库函数,new/delete 是c++的运算符。两者都可以申请动态内存和释放内存。
对于非内部数据类型的对象而言,光用malloc/free是无法满足动态对象的要求的。对象在创建时需要自动调用构造函数,在消亡时需要调用析构函数。由于malloc/free是库函数而不是运算符,不在编译器的控制权限之内,不能把自动执行构造函数和析构函数的任务强加给malloc/free。举例说明:

malloc/free 与 new/delete 区别
#include <iostream>
#include <cstdlib>
using namespace std;
class A
{
    public:
        A(void);
        ~A(void);
};
A::A(void)
{
    cout << "Initialize" << endl;
}
A::~A(void)
{
    cout << "Destroy" << endl;
}

int main()
{
    A *a = (A *)malloc(sizeof(A) * 10);
    free(a);
    a = NULL;
    cout << "***********" << endl;
    A *b = new A[3];
    delete [] b;
}
malloc/free 与 new/delete 区别

运行结果

malloc/free 与 new/delete 区别

可以看出利用malloc/free来完成分配动态时,是无法自动调用构造和析构函数的。而new/free可以轻松胜任。

对于内部数据类型来说,因为其对对象没有构造与析构函数,因此二者是等价的。




本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3247919.html,如需转载请自行联系原作者