簡體   English   中英

如果構造函數拋出異常,new 分配的內存會發生什么?

[英]What happens to the memory allocated by `new` if the constructor throws?

這段代碼會導致內存泄漏嗎?

#include <stdexept>

class MyClass
{
public:
    MyClass()
    {
        throw std::runtime_error("Test");
    }
};

int main()
{
    try
    {
        MyClass * myClass = new MyClass;
    }
    catch (const std::exception & exc)
    {
        // Memory leak?
    }
    return 0;
}

new分配的內存永遠不會被刪除。 這是在內部處理的,還是實際的內存泄漏?

在異常傳播之前,內存將被自動釋放。

這是必不可少的,因為 a) 程序永遠不會收到指向 free 的指針,並且 b) 即使收到了,它也沒有可移植的方式來實際釋放它,因為內存永遠不會成為您可以刪除的對象。

內存將被正確釋放。

SO的相關問題。

  • 在構造函數中拋出異常是否不安全?
  • C++:如果構造函數可能拋出異常,則處理資源(參考 FAQ 17.4)
  • prasoon@prasoon-desktop ~ $ cat noleak.cpp && g++ noleak.cpp && valgrind --leak-check=full ./a.out
    #include <stdexcept>
    
    class MyClass
    {
    public:
        MyClass()
        {
            throw std::runtime_error("Test");
        }
    };
    
    int main()
    {
        try
        {
            MyClass * myClass = new MyClass;
        }
        catch (const std::exception & exc)
        {
            // Memory leak?
        }
        return 0;
    }
    ==3652== Memcheck, a memory error detector
    ==3652== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
    ==3652== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
    ==3652== Command: ./a.out
    ==3652== 
    ==3652== 
    ==3652== HEAP SUMMARY:
    ==3652==     in use at exit: 0 bytes in 0 blocks
    ==3652==   total heap usage: 3 allocs, 3 frees, 106 bytes allocated
    ==3652== 
    ==3652== All heap blocks were freed -- no leaks are possible
    ==3652== 
    ==3652== For counts of detected and suppressed errors, rerun with: -v
    ==3652== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 17 from 6)
    prasoon@prasoon-desktop ~ $ 
    

    $15.2/2 - “部分構造或部分銷毀的對象將為其所有完全構造的基類和非變體成員執行析構函數,即,對於主構造函數(12.6.2)已完成執行的子對象並且析構函數尚未開始執行。類似地,如果對象的非委托構造函數已完成執行並且該對象的委托構造函數以異常退出,則將調用該對象的析構函數。如果該對象是在新分配的-expression,匹配的釋放函數(3.7.4.2, 5.3.4, 12.5),如果有的話,會被調用來釋放對象占用的存儲空間。

    暫無
    暫無

    聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

     
    粵ICP備18138465號  © 2020-2024 STACKOOM.COM