C++: delete vs. free and performance

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

    As others have pointed out deleting (or freeing) a NULL pointer will not do anything. However if you had allocated some memory then whether to use free() or delete depends upon the method you used to allocate them. For example, if you had used malloc() to allocate memory then you should free() and if you had used new to allocate then you should use delete. However, be careful not to mix the memory allocations. Use a single way to allocate and deallocate them.

    For the second question, it will be very difficult to generalize without seeing the actual code. It should be taken on a case by case basis.

提交回复
热议问题