Tuesday 29 July 2014

[C++] Why we need new/delete in C++? Can't malloc/free do the same thing?

The difference between malloc/free and new/delete is malloc/free are standard library, and new/delete are operator.
#include <iostream>
#include <cstdlib>

using namespace std;

class Obj
{
public :
    Obj(void){ cout << "Constructor" << endl; }
    ~Obj(void){ cout << "Destructor" << endl; }
    void Initialize(void){ cout << "Initialization" << endl; }
    void Destroy(void){ cout << "Destroy" << endl; }
};

void UseMallocFree(void)
{
    Obj  *a = (Obj *)malloc(sizeof(Obj));
    a->Initialize();

    //…

    a->Destroy();
    free(a);

}

void UseNewDelete(void)
{
    Obj  *a = new Obj;

    //…

    delete a;
}

int main()
{
    cout << "UseMallocFree" << endl;
    UseMallocFree();
    cout << endl << "UseNewDelete" << endl;
    UseNewDelete();

    return 0;
}
UseMallocFree
Initialization
Destroy

UseNewDelete
Constructor
Destructor

Ref.: http://fanqiang.chinaunix.net/a4/b2/20020722/060200273_b.html

No comments:

Post a Comment