Should new/new[] match delete/delete[]?

后端 未结 3 1008
执念已碎
执念已碎 2020-12-07 06:29

I knew that when we allocate memory by using new/new[], then we should release the memory by using the delete/delete[] respectively.

Here is the question,

Ca

3条回答
  •  北海茫月
    2020-12-07 06:48

    No, you should match the non-array form of new with non-array delete, and likewise for the array forms.

    See the C++ FAQ Lite section on Freestore Management

    This is especially good: http://www.parashift.com/c%2B%2B-faq-lite/freestore-mgmt.html#faq-16.12

    [16.12] What if I forget the [] when deleteing array allocated via new T[n]?

    All life comes to a catastrophic end.

    It is the programmer's —not the compiler's— responsibility to get the connection between new T[n] and delete[] p correct. If you get it wrong, neither a compile-time nor a run-time error message will be generated by the compiler. Heap corruption is a likely result. Or worse. Your program will probably die.

提交回复
热议问题