Does delete[] call destructors?

佐手、 提交于 2019-11-30 18:34:59

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.

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.

The answer is yes. Destructor for each object is called.

On a related note, you should try to avoid using delete whenever possible. Use smart pointers (e.g.,unique_ptr, shared_ptr) and STL containers (e.g., std::vector, std::array) instead.

delete[] objects is similar (but not identical) to:

for (i = 0; i < num_of_objects; ++i) {
    delete objects[i];
}

since delete calls the destructor, you can expect delete[] to do the same.

Nikolai Fetissov

delete [] does call the destructor for each element of the array. Same happens for a member array (your T objects[100]).

You want to keep it as pointer, and design the destructor (and copy constructor, and copy assignment operator, see rule of three/five) for your template to deal with "non-sensible" values pointed to by objects.

Yes, delete[] guarantees destructors are called on every object.

Depending on your use case, using Boost pointer containers, or simply containers of smart pointers, might make it a lot easier to have (exception safe) collection of pointers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!