gpt4 book ai didi

c++ - 从 C++ 函数调用 exit() 来终止程序是否安全?

转载 作者:行者123 更新时间:2023-12-01 22:56:13 25 4
gpt4 key购买 nike

我在 Stack Overflow、Microsoft 文档和 cplusplus.com 上阅读了几个问题。有些人声称 exit() 会正常终止程序,就像 return 0; 从 main 中一样。其他人声称 exit() 不会调用所有析构函数等。所以我想知道是否有人可以提供帮助。

编辑:正如有人问的那样,我添加了一些我想终止程序的代码块。我使用 C++20

HKEY newKey;

RegOpenKey(HKEY_CURRENT_USER, R"(Software\Microsoft\Windows\CurrentVersion\Run)", &newKey);
LONG result = RegSetValueEx(newKey, value, 0, REG_SZ, (LPBYTE)filePath, lstrlen(filePath));
RegCloseKey(newKey);

if(result != ERROR_SUCCESS){
MessageBox(nullptr, "Could not add to startup", "Error", MB_ICONERROR);
exit(1);
}
int i = line.find(':');

if(i == std::string::npos){
MessageBox(nullptr, "File is incorrectly formatted", "Error", MB_ICONERROR);
exit(1);
}
info.open(infoPath);

if(info.fail()){
MessageBox(nullptr, "info.txt did not open", "Error", MB_ICONERROR);
exit(1);
}

我链接了我读过的关于这个的帖子:

How to end C++ code

https://cplusplus.com/forum/beginner/4589/

How to exit program execution in C++?

https://learn.microsoft.com/en-us/cpp/cpp/program-termination?view=msvc-170

https://cplusplus.com/reference/cstdlib/exit/

提前致谢

最佳答案

Some claim that exit() terminates the program normally, just as a return 0; would from main

std::exit 无论如何都会被调用,作为标准应用程序生命周期的一部分。 Quote from CPPReference :

Returning from the main function, either by a return statement or byreaching the end of the function performs the normal functiontermination (calls the destructors of the variables with automaticstorage durations) and then executes std::exit, passing the argumentof the return statement (or ​0​ if implicit return was used) asexit_code.


Others claim that exit() doesn't call all the destructors, etc

这是真的,但它并没有取消第一个声明。 IE。如果你的类的析构函数没有任何可以在程序中存活的副作用,那么本地是否被正确销毁并不重要,因为你的进程的整个内存在程序终止后被释放。 std::exit 但是 calls destructors of objects with static and thread local storage duration :

The destructors of objects with thread local storage duration that areassociated with the current thread, the destructors of objects withstatic storage duration, and the functions registered with std::atexitare executed concurrently

关于c++ - 从 C++ 函数调用 exit() 来终止程序是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73199739/

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