This question already has answers here:
Who deletes the memory allocated during a “new” operation which has exception in constructor?
                                
                                    (8个答案)
                                
                        
                                6年前关闭。
            
                    
我想知道是否动态分配了对象,并且构造函数抛出异常,是否仍然需要删除该对象?

class Doom
{
public:

   Doom() { throw 0; }

private:

   int pad;

};

int main()
{
    try
    {
        // memory is allocated for Doom but construction fails
        // is the memory deallocated if construction fails here ?
        Doom* doom = new Doom();
    }
    catch(int ex)
    {
        // ...
    }
}

最佳答案

否。没有什么要删除的,因为该对象从未构造过。编译器将负责释放分配的内存。

09-06 20:32