What happens if delete[] p fails?

后端 未结 6 845
醉酒成梦
醉酒成梦 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:33

    I can not see it explicitly called out in the standard:

    Just that they will be called in reverse order of creation

    5.3.5 Delete [expr.delete]

    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).

    And that the memory deallocation will be done even if the exception is thrown:

    7 If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will call a deallocation function (3.7.4.2). Otherwise, it is unspecified whether the deallocation function will be called. [ Note: The deallocation function is called regardless of whether the destructor for the object or some element of the array throws an exception. — end note ]

    I tried the following code in G++ and it shows that that no more destructors get called after the exception:

    #include 
    int id = 0;
    class X
    {
        public:
             X() {   me = id++; std::cout << "C: Start" << me << "\n";}
            ~X() {   std::cout << "C: Done " << me << "\n";
                     if (me == 5) {throw int(1);}
                 }
        private:
            int me;
    };
    
    int main()
    {
        try
        {
            X       data[10];
        }
        catch(...)
        {
            std::cout << "Finished\n";
        }
    }
    

    Execute:

    > g++ de.cpp
    > ./a.out
    C: Start0
    C: Start1
    C: Start2
    C: Start3
    C: Start4
    C: Start5
    C: Start6
    C: Start7
    C: Start8
    C: Start9
    C: Done 9
    C: Done 8
    C: Done 7
    C: Done 6
    C: Done 5
    Finished
    

    Which all leads back to this (very old answer):
    throwing exceptions out of a destructor

提交回复
热议问题