【问题标题】:When do destructors get called when multiple exceptions handlings are involved?当涉及多个异常处理时,何时调用析构函数?
【发布时间】:2012-06-16 05:37:57
【问题描述】:

在下面的代码中,如main()所示,分两种情况抛出异常。

#include <iostream>

// Our own exception classes - just for fun.
class myExceptionClassA 
{
    public:
    myExceptionClassA () {std::cout << "\nWarning: Division by zero isn't allowed.\n";}
};

class myExceptionClassB
{
    public:
    myExceptionClassB () {std::cout << "\nWarning: Division by dividend isn't allowed.\n";}
};

class divisionClass
{
    private:
    int *result;

    public:
    divisionClass () 
    {
        // Allocating memory to the private variable.
        result = new int;
    }

    /* 
        The class function `doDivide`:
        1. Throws above defined exceptions on the specified cases.
        2. Returns the division result.
    */
    int doDivide (int toBeDividedBy) throw (myExceptionClassA, myExceptionClassB)
    {
        *result       = 200000;

        // If the divisor is 0, then throw an exception.
        if (toBeDividedBy == 0)
        {
            throw myExceptionClassA ();
        }
        // If the divisor is same as dividend, then throw an exception.
        else if (toBeDividedBy == *result)
        {
            throw myExceptionClassB ();
        }

        // The following code won't get executed if/when an exception is thrown.
        std :: cout <<"\nException wasn't thrown. :)";

        *result = *result / toBeDividedBy;
        return *result;
    }

    ~divisionClass () 
    {
        std::cout << "\ndddddddddd\n";
        delete result;
    }
};

int main ()
{
    divisionClass obj;
    try
    {
        obj.doDivide (200000);
    }
    catch (myExceptionClassA) {}
    catch (myExceptionClassB) {}

    try
    {
        obj.doDivide (3);
    }
    catch (myExceptionClassA) {}
    catch (myExceptionClassB) {}

    try
    {
        obj.doDivide (0);
    }
    catch (myExceptionClassA) {}
    catch (myExceptionClassB) {}

    try
    {
        obj.doDivide (4);
    }
    catch (myExceptionClassA) {}
    catch (myExceptionClassB) {}

    return 0;
}

- 两个异常类打印语句都被打印。
- 析构函数中的语句只打印一次。
- Valgrind 没有显示任何内存泄漏。

anisha@linux-y3pi:~/Desktop> g++ exceptionSafe3.cpp -Wall
anisha@linux-y3pi:~/Desktop> valgrind ./a.out 
==18838== Memcheck, a memory error detector
==18838== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==18838== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==18838== Command: ./a.out
==18838== 

Warning: Division by dividend isn't allowed.

Exception wasn't thrown. :)
Warning: Division by zero isn't allowed.

Exception wasn't thrown. :)
dddddddddd
==18838== 
==18838== HEAP SUMMARY:
==18838==     in use at exit: 0 bytes in 0 blocks
==18838==   total heap usage: 3 allocs, 3 frees, 262 bytes allocated
==18838== 
==18838== All heap blocks were freed -- no leaks are possible
==18838== 
==18838== For counts of detected and suppressed errors, rerun with: -v
==18838== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
anisha@linux-y3pi:~/Desktop> 

不应该调用析构函数 3 次 - 两次用于异常,一次用于返回语句吗?

请解释我遗漏的一点。


现在我通过删除 main() 中的所有 try catch 块来尝试它。
析构函数根本没有被调用?

anisha@linux-y3pi:~/Desktop> valgrind ./a.out 
==18994== Memcheck, a memory error detector
==18994== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==18994== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==18994== Command: ./a.out
==18994== 

Warning: Division by dividend isn't allowed.
terminate called after throwing an instance of 'myExceptionClassB'
==18994== 
==18994== HEAP SUMMARY:
==18994==     in use at exit: 133 bytes in 2 blocks
==18994==   total heap usage: 3 allocs, 1 frees, 165 bytes allocated
==18994== 
==18994== LEAK SUMMARY:
==18994==    definitely lost: 0 bytes in 0 blocks
==18994==    indirectly lost: 0 bytes in 0 blocks
==18994==      possibly lost: 129 bytes in 1 blocks
==18994==    still reachable: 4 bytes in 1 blocks
==18994==         suppressed: 0 bytes in 0 blocks
==18994== Rerun with --leak-check=full to see details of leaked memory
==18994== 
==18994== For counts of detected and suppressed errors, rerun with: -v
==18994== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
Aborted
anisha@linux-y3pi:~/Desktop>

【问题讨论】:

  • 当抛出异常时,堆栈展开调用该范围内所有创建对象的析构函数({,})不会破坏拥有的对象。
  • 如果一个异常被抛出并且从未被捕获,那么它是实现定义堆栈展开或abort()被首先调用,看起来你的实现没有展开堆栈,并且按照标准是允许的。
  • 为什么你认为应该调用析构函数?抛出异常时,只有在抛出异常的范围之外的对象才会被破坏。在您的情况下,没有仅在 divisionClass::doDivide() 的主体内定义的对象。
  • @Walter why do you think the destructor should be called? 实际上,我正在研究 RAII,它说如果你将方法放在一个类中,析构函数将负责释放内存并引发抛出(wrt 异常安全代码)。跨度>
  • @AnishaKaul:这个类似的 Q here 可能会帮助你更好地理解。

标签: c++ exception-handling destructor


【解决方案1】:

当您捕获异常时,堆栈会在异常抛出点和异常被捕获点之间“展开”。这意味着这两个点之间范围内的所有自动变量都将被销毁——try 中与 catch 匹配的任何内容对应的所有内容都与异常匹配。

您的对象objmain 函数中的自动变量,在try 之外。因此,当堆栈展开时,它不会被破坏。您的代码依赖于这一事实——在第一个 catch 之后,您再次调用 doDivide,所以它最好不要被破坏。

如果您根本没有捕获异常,那么在程序终止之前堆栈是否展开(C++11 中的 15.3/9)由实现定义。看起来好像在您的第二个测试中,没有任何 catch 子句,它不是。

这意味着如果您希望您的 RAII 对象“工作”,那么您不能在您的程序中允许未捕获的异常。你可以这样做:

int main() {
    try {
        do_all_the_work();
    } catch (...) {
        throw; // or just exit
    }
}

现在你可以保证do_all_the_work 中的任何自动变量都会在异常转义函数时被销毁。缺点是您可能从调试器中获得的信息较少,因为它忘记了未捕获异常的原始抛出位置。

当然,您的程序中的代码仍然可以防止您的obj 被破坏,例如通过调用abort()

【讨论】:

    【解决方案2】:

    从方法中抛出异常不会破坏拥有它的对象。只有当它被删除或超出范围时(在这种情况下,在 main() 的末尾),它才会被销毁并调用析构函数。

    【讨论】:

      【解决方案3】:

      消息打印在divisionClass 的析构函数中。您只有一个该类型的对象,它在main 的末尾被销毁。

      【讨论】:

      • 那么,就是说抛出异常的时候不调用析构函数?
      • @AnishaKaul 如果你抓住它,不。如果您让它传播(假设您在另一个从 main 调用的方法中执行此操作,并在 main 中捕获异常),那么是的,但那是因为对象范围结束了。
      • @AnishaKaul:堆栈展开会破坏在引发异常的范围内创建的对象(并因此调用析构函数)。
      • Luchain,`如果你让它传播`这是什么意思?如果我没有捕捉到异常,我会看看会发生什么。
      • @AnishaKaul 确实如此,但释放内存的例外情况并非如此。
      【解决方案4】:

      当从抛出异常的点开始调用堆栈的某处有匹配的catch 处理程序时,保证会发生堆栈展开。您可以像这样简化和可视化您的堆栈:

      +-------------------+
      | locals            | obj.doDivide()
      +-------------------+
      |                   | try {}
      +-------------------+
      | catch { }         |
      |                   | main()
      | DivisionClass obj |
      +-------------------+
      

      只有堆栈的下面部分(在上面的图片中)被展开并且相应的对象被销毁。包含 divisonClass 对象的堆栈部分保持不变,直到 main() 退出。

      试试这段代码,看看有什么不同:

      void foo()
      {
          divisionClass obj;
          obj.doDivide(0);
      }
      
      int main()
      {
          try {
              foo();
          }
          catch (myExceptionClassA) {
              std::cout << "Check point.\n";
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 2013-11-07
        • 2016-08-12
        • 2012-04-15
        • 2011-06-04
        • 2014-05-26
        相关资源
        最近更新 更多