delete[] an array of objects

后端 未结 5 1221
孤街浪徒
孤街浪徒 2020-11-29 04:12

I have allocated and array of Objects

Objects *array = new Objects[N];

How should I delete this array? Just

delete[] array         


        
5条回答
  •  孤城傲影
    2020-11-29 04:22

    Every use of new should be balanced by a delete, and every use of new[] should be balanced by delete[].

    for(int i=0;i

    That would be appropriate only if you initialized the array as:

    Objects **array = new Objects*[N];
    for (int i = 0; i < N; i++) { 
        array[i] = new Object;
    }
    

    The fact that your original code gave you a compilation error is a strong hint that you're doing something wrong.

    BTW, obligatory: avoid allocating arrays with new[]; use std::vector instead, and then its destructor will take care of cleanup for you. Additionally it will be exception-safe by not leaking memory if exceptions are thrown.

提交回复
热议问题