gpt4 book ai didi

c++ - 在 main 之前退出程序是否是明确定义的行为?

转载 作者:可可西里 更新时间:2023-11-01 15:22:34 27 4
gpt4 key购买 nike

在调用 main 之前执行代码绝对是可能的,如 this question 中的许多示例所示.

但是,如果在主前代码中,程序被告知通过 std::exitstd::abort 退出怎么办?由于 main 被定义为程序的开始,那么在开始之前退出会有什么后果?

在每个部分打印一些东西后,我得到以下结果:

格式:
部分:输出

主要:主要
Init(在main之前调用):init
退出(在Init中用std::atexit设置):exiting



样本运行:

在不退出的情况下调用 Init:

init
main
returns 0

初始化调用 std::exit(0):

init
returns 0

Init 调用 std::abort:

init
crashes and returns 3 on Windows with GCC 4.7.2
crashes and brings up the usual box with VS11
returns 0 on LiveWorkSpace

Init 设置处理程序并调用 std::exit(0):

init
exiting
returns 0

Init 设置处理程序并调用 std::abort:

init
same deal as without the handler

在搜索时,我看到了这个问题:Is there any way a C/C++ program can crash before main()? .但是,它没有回答我想知道的问题:是否有任何这种行为,在 main std::exitstd::abort,定义明确?这是任何未定义的行为吗?

最佳答案

简短的回答是:(几乎)没有任何后果。如果您意外调用 exit,一些析构函数可能不会被调用,但仅此而已。
通常,不调用析构函数不是最干净的方法,但最终结果还是一样的。

当进程终止时(通过 exitabort 或仅仅通过段错误或其他原因),句柄(内核对象、文件等)将关闭,并且与程序地址空间关联的内存由操作系统回收。

也没什么其他的,因为当您调用 exitabort 时,您基本上是在请求程序终止(这些函数永远不会返回!)所以您真的不能指望此后会发生任何事情。

请注意,在 main 之前注册一个像 Init 这样的函数是非标准的东西,但是你可以通过在全局中使用构造函数来获得相同的效果。

关于c++ - 在 main 之前退出程序是否是明确定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13214661/

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