gpt4 book ai didi

c++ - 当涉及多个异常处理时,何时调用析构函数?

转载 作者:太空狗 更新时间:2023-10-29 23:53:25 26 4
gpt4 key购买 nike

在下面的代码中,抛出的异常有两种情况,如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 block 来尝试它。
析构函数根本不会被调用?

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>

最佳答案

当您捕获异常时,堆栈会在异常抛出点和捕获点之间“展开”。这意味着这两点之间范围内的所有自动变量都将被销毁——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()

关于c++ - 当涉及多个异常处理时,何时调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11011896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com