exit() 或异常会阻止调用作用域结束析构函数吗?

发布于 2024-08-29 13:30:39 字数 261 浏览 4 评论 0原文

假设我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无风消散 2024-09-05 13:30:39

如果调用exit,析构函数将不会被调用。

来自 C++ 标准 (§3.6.1/4):

调用函数

void exit(int);

(18.3) 中声明会终止程序而不离开当前块,因此不会破坏任何具有自动存储持续时间的对象 (12.4)。如果在销毁具有静态存储持续时间的对象期间调用 exit 来结束程序,则该程序具有未定义的行为。

If you call exit, the destructor will not be called.

From the C++ standard (§3.6.1/4):

Calling the function

void exit(int);

declared in <cstdlib> (18.3) terminates the program without leaving the current block and hence without destroying any objects with automatic storage duration (12.4). If exit is called to end a program during the destruction of an object with static storage duration, the program has undefined behavior.

暮年慕年 2024-09-05 13:30:39

是的,调用 exit() 意味着析构函数不会被调用:

调用函数 void exit(int);
(18.3) 中声明
终止程序而不离开
当前块,因此没有
自动摧毁任何物体
储存期限(12.4)。如果退出是
调用期间结束程序
用静电破坏物体
存储持续时间,程序有
未定义的行为。

另一方面,如果抛出异常,则将调用析构函数。这是C++中异常安全的基础。

Yes, calling exit() means the destructor will not be called:

Calling the function void exit(int);
declared in <cstdlib> (18.3)
terminates the program without leaving
the current block and hence without
destroying any objects with automatic
storage duration (12.4). If exit is
called to end a program during the
destruction of an object with static
storage duration, the program has
undefined behavior.

If an exception is thrown, on the other hand, the destructor will be called. This is the basis of exception safety in C++.

夏末 2024-09-05 13:30:39

只要程序中的某些内容捕获了异常,异常就会调用析构函数。如果异常退出 main() 函数而未被捕获,则标准不要求运行时展开堆栈进行清理。

main() 函数中使用 a

try{
  // code
}catch(...){ //that elipsis should actually appear in your code
             //it doesn't mean I omitted code here.
  //code
}

将保证捕获每个异常,并调用所有析构函数。

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

try{
  // code
}catch(...){ //that elipsis should actually appear in your code
             //it doesn't mean I omitted code here.
  //code
}

in your main() function will guarantee that every exception is caught, and all destructors are called.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文