Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

c++ - delete[] an array of objects

I have allocated and array of Objects

Objects *array = new Objects[N];

How should I delete this array? Just

delete[] array;

or with iterating over the array's elements?

for(int i=0;i<N;i++)
    delete array[i];
delete[];

Thanks

UPDATE:

I changed loop body as

delete &array[i];

to force the code to compile.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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<N;i++)
    delete array[i];
delete[] array;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...