本文介绍了它是明确定义的行为退出程序之前main?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这绝对可以在 main 调用之前执行代码,如

但是,什么都不是,你可以打印任何东西在前进入主要功能>这个问题。如果在前置主代码中,程序被告知要通过 std :: exit std :: abort ?由于 main 被定义为程序的开始,在开始之前退出会有什么后果?



在每个部分打印,我得到以下结果:



格式:

部分输出



main

Init(在main之前调用) init

退出(在Init中设置 std :: atexit 退出






示例运行:



未退出时调用Init

Init调用std :: exit 0)

$


初始化调用std :: abort:

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

Init set handler and calls std :: abort: strong>

在搜索时,我看到了这个问题:有没有什么办法C / C ++程序可以在main()之前崩溃?但是,它不回答我想知道的:这是任何行为,调用 std :: exit std :: abort 之前 main ,定义明确?是否有任何未定义的行为?

简短的回答是:如果你意外地调用 exit ,一些析构函数可能不会被调用,但是实际上是这样。

通常,不调用析构函数不是最干净的方式,



当进程终止时(通过退出 abort 或简单地通过segfaulting或其他原因),句柄(内核对象,文件等)被关闭,并且与程序的地址空间相关联的内存被操作系统回收。



没有其他的东西,因为当你调用 exit abort ,你基本上要求程序终止(这些函数永远不会返回!),所以你真的不能期望以后发生任何事情。



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


It's definitely possible to execute code before main is called, as seen by many examples in this question.

However, what if in that pre-main code, the program is told to exit via std::exit or std::abort? Since main is defined as the start of a program, what consequences are there from exiting before the start?

Upon printing something in each section, I get the following results:

Format:
Section: output

Main: main
Init (called before main): init
Exit (set up with std::atexit inside Init): exiting



Sample runs:

Init called without exiting:

Init calls std::exit(0):

Init calls std::abort:

Init sets handler and calls std::exit(0):

Init sets handler and calls std::abort:

While searching, I saw this question: Is there any way a C/C++ program can crash before main()?. However, it doesn't answer what I want to know: Is any of this behaviour, calling std::exit or std::abort before main, well-defined? Is any of this undefined behaviour?

解决方案

The short answer is: there are (almost) no consequences. Some destructors may not be called if you unexpectedly call exit, but that's pretty much it.
Generally, not calling destructors is not the cleanest possible way, but then again the end result will be the same.

When a process terminates (via exit or abort or simply by segfaulting, or another reason), handles (kernel objects, files, etc.) are closed, and the memory associated with the program's address space is reclaimed by the operating system.

There is not much else to it either, because when you call exit or abort, you're basically requesting that the program terminates (these functions never return!) so you really can't expect anything to happen thereafter.

Note that registering a function like Init to be called before main is non-standard stuff, but you can get the same effect by having a constructor in a global.

这篇关于它是明确定义的行为退出程序之前main?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 16:12