C++: delete vs. free and performance

后端 未结 7 1275
天命终不由人
天命终不由人 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:40

    Question one: nothing will happen.

    From the current draft of ISO/IEC 14882 (or: C++):

    20.8.15 C Library [c.malloc]

    The contents [of , that is: where free lives,] are the same as the Standard C library [(see intro.refs for that)] header , with the following changes: [nothing that effects this answer].

    So, from ISO/IEC 9899:1999 (or: C):

    7.20.3.2 The free function

    If [the] ptr [parameter] is a null pointer, no action occurs.

    From the C++ standard again, for information about delete this time:

    3.7.4.2 Deallocation functions [basic.stc.dynamic.deallocation]

    The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect.

    See also:

    • What is the difference between new/delete and malloc/free?
    • What happens when you try to free() already freed memory in c?

提交回复
热议问题