Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does delete[] call destructors?

I am writing a template class which internally manages an array of the given type. Like this:

template<typename T>
class Example {
    // ...
private:
    T* objects; // allocated in c'tor (array), deleted in d'tor
    // ...
};

I was wondering if C++ calls the destructor of each object in objects when I delete it via delete[] objects;.

I need to know this, because the objects in my class do not contain sensible values all the time, so the destructors should not be called when they don't.

Additionally, I'd like to know if the destructors would be called if I declared a fixed-sized array like T objects[100] as part of Example<T>.

like image 824
Mixthos Avatar asked Jun 27 '13 13:06

Mixthos


2 Answers

If T has a destructor then it will be invoked by delete[]. From section 5.3.5 Delete of the c++11 standard (draft n3337), clause 6:

If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).

The destructor for a type T will also be invoked for each element in an array of T[] when the array is not dynamically allocated and array goes out of scope (lifetime ends).


I need to know this, because the objects in my class do not contain sensible values all the time, so the destructors should not be called when they don't.

But, there seems to be a very significant problem with an object that can acquire a state where it cannot be destructed.

like image 91
hmjd Avatar answered Oct 27 '22 01:10

hmjd


Yes, the destructor will be called for all objects in the array when using delete[]. But that shouldn't be an issue, since the constructor was called for all objects in the array when you used new[] (you did, right ?) to allocate it.

If a constructed object can be in such a state that calling the destructor would be invalid, then there's something seriously wrong with your object. You need to make your destructor work in all cases.

like image 20
Sander De Dycker Avatar answered Oct 27 '22 00:10

Sander De Dycker