What happens if delete[] p fails?

后端 未结 6 832
醉酒成梦
醉酒成梦 2021-02-07 03:52

Suppose I have a pointer to a dynamically allocated array of 10 elements:

T* p = new T[10];

Later, I want to release that array:



        
6条回答
  •  不思量自难忘°
    2021-02-07 04:24

    If an exception is thrown, it is thrown. The object that failed to destruct is obviously not properly destroyed, and neither are the ones remaining in the array.

    If you use a vector, the problem is the same, just not in your code. :-)

    So, throwing destructors is just a Bad Idea(tm).


    Like @Martin shows below, the object that did thrown is formally non-existent as soon as we enter the destructor. The others might have their memory reclaimed as well.

    However, it obviously contained some complicated things that were not properly of flusher flushed. If that object, and the others following it in the array, contained some mutex locks, open files, database caches, or shared_ptrs, and none of those had their destructors run, we are likely in BIG trouble.

    Having std::terminate called at that point, to put the program out of its misery, seems like something you would wish for!

提交回复
热议问题