delete vs delete[] operators in C++

后端 未结 6 1316
[愿得一人]
[愿得一人] 2020-11-22 06:13

What is the difference between delete and delete[] operators in C++?

6条回答
  •  清歌不尽
    2020-11-22 06:49

    This the basic usage of allocate/DE-allocate pattern in c++ malloc/free, new/delete, new[]/delete[]

    We need to use them correspondingly. But I would like to add this particular understanding for the difference between delete and delete[]

    1) delete is used to de-allocate memory allocated for single object

    2) delete[] is used to de-allocate memory allocated for array of objects

    class ABC{}
    
    ABC *ptr = new ABC[100]
    

    when we say new ABC[100], compiler can get the information about how many objects that needs to be allocated(here it is 100) and will call the constructor for each of the objects created

    but correspondingly if we simply use delete ptr for this case, compiler will not know how many objects that ptr is pointing to and will end up calling of destructor and deleting memory for only 1 object(leaving the invocation of destructors and deallocation of remaining 99 objects). Hence there will be a memory leak.

    so we need to use delete [] ptr in this case.

提交回复
热议问题