exit() 或异常会阻止调用作用域结束析构函数吗?
假设我有以下代码:
struct mytype
{
~mytype() { /* do something like call Mix_CloseAudio etc */ }
};
int main()
{
mytype instant;
init_stuff();
start();
return 0;
}
即使从 start() 内部的某处使用 exit() ,是否也保证调用该析构函数?
Let's say I have the following code:
struct mytype
{
~mytype() { /* do something like call Mix_CloseAudio etc */ }
};
int main()
{
mytype instant;
init_stuff();
start();
return 0;
}
Is that destructor guaranteed to be called even if exit() is used from somewhere inside start() ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果调用
exit
,析构函数将不会被调用。来自 C++ 标准 (§3.6.1/4):
If you call
exit
, the destructor will not be called.From the C++ standard (§3.6.1/4):
是的,调用 exit() 意味着析构函数不会被调用:
另一方面,如果抛出异常,则将调用析构函数。这是C++中异常安全的基础。
Yes, calling exit() means the destructor will not be called:
If an exception is thrown, on the other hand, the destructor will be called. This is the basis of exception safety in C++.
只要程序中的某些内容捕获了异常,异常就会调用析构函数。如果异常退出 main() 函数而未被捕获,则标准不要求运行时展开堆栈进行清理。
在
main()
函数中使用 a将保证捕获每个异常,并调用所有析构函数。
Exceptions will call destructors, so long as something in the program catches the exception. If the exception exits the main() function without being caught, the standard does not require the runtime to unwind the stack to clean up.
Using a
in your
main()
function will guarantee that every exception is caught, and all destructors are called.