C++: delete vs. free and performance

后端 未结 7 1391
天命终不由人
天命终不由人 2021-01-30 11:07
  1. Consider:

    char *p=NULL;
    free(p) // or
    delete p;
    

    What will happen if I use free and delete on p?

7条回答
  •  广开言路
    2021-01-30 11:33

    Some performance notes about new/delete and malloc/free:

    malloc and free do not call the constructor and deconstructor, respectively. This means your classes won't get initalized or deinitialized automatically, which could be bad (e.g. uninitalized pointers)! This doesn't matter for POD data types like char and double, though, since they don't really have a ctor.

    new and delete do call the constructor and deconstructor. This means your class instances are initalized and deinitialized automatically. However, normally there's a performance hit (compared to plain allocation), but that's for the better.

    I suggest staying consistent with new/malloc usage unless you have a reason (e.g. realloc). This way, you have less dependencies, reducing your code size and load time (only by a smidgin, though). Also, you won't mess up by free'ing something allocated with new, or deleting something allocated with malloc. (This will most likely cause a crash!)

提交回复
热议问题