delete[] an array of objects

后端 未结 5 1223
孤街浪徒
孤街浪徒 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:21

    Not only is

    delete [] array;
    

    enough, but if you do

    for(int i=0;i

    you'll be causing undefined behavior, because

    delete &array[i];
    

    will be deleting things that weren't returned by a new operation.

    Not to mention that the subsequent delete[] array; will call the destructor for all the objects that just had destructors called in the loop.

    So don't do that.

提交回复
热议问题