代码之家  ›  专栏  ›  技术社区  ›  StackedCrooked

如果构造函数抛出,new分配的内存会发生什么变化?

c++
  •  17
  • StackedCrooked  · 技术社区  · 15 年前

    #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 从未被删除。这是内部处理,还是实际内存泄漏?

    3 回复  |  直到 15 年前
        1
  •  16
  •   Marcelo Cantos    15 年前

    在异常传播之前,内存将被自动释放。

    这一点很重要,因为a)程序从来没有收到指向free的指针,b)即使它收到了,它也没有可移植的方法来真正释放它,因为内存从来没有成为可以删除的对象。

        2
  •  12
  •   Community Mohan Dere    8 年前

    与此相关的问题。

  • Is it ever not safe to throw an exception in a constructor?
  • C++ : handle resources if constructors may throw exceptions (Reference to 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 ~ $ 
    
        3
  •  4
  •   Chubsdad    15 年前

    $15.2/2-“部分 建造或部分毁坏 完全构造的基类 以及非变体成员,即 建造师(12.6.2)已完成 执行和析构函数没有 却开始执行死刑。同样,如果 对象已完成执行,并且 带有异常的对象 将调用析构函数。 对象是在 新表达式,匹配 解除分配功能(3.7.4.2,5.3.4, "