当我们使用 atexit() 时,不会为本地对象调用析构函数

Destructor not called for local objects when we use atexit()

本文关键字:对象 析构函数 调用 我们 atexit      更新时间:2023-10-16

请帮忙:我知道析构函数和atexit(),也知道以下内容:atexit() 注册一个在程序终止时要调用的函数(例如,当 main() 调用返回或当 exit() 在某处显式调用时)。

当调用 exit() 时,静态对象被销毁(析构函数被调用),但局部变量范围内的对象不会被销毁,当然也不会动态分配的对象(这些对象只有在显式调用 delete 时才会被销毁)。

下面的代码给出的输出为:在退出处理程序静态 dtor

你能帮我知道为什么当我们使用 atexit() 时不会调用本地对象的析构函数吗?

提前致谢:

class Static {
public:
    ~Static() 
        {
        std::cout << "Static dtorn";
        }
    };
class Sample {
public:
    ~Sample() 
        {
        std::cout << "Sample dtorn";
        }
    };
class Local {
public:
    ~Local() 
        {
        std::cout << "Local dtorn";
        }
    };
Static static_variable; // dtor of this object *will* be called
void atexit_handler()
    {
    std::cout << "atexit handlern";
    }
int main()
    {
    Local local_variable; 
    const int result = std::atexit(atexit_handler); 
    Sample static_variable; // dtor of this object *will not* be called
    std::exit(EXIT_SUCCESS);//succesful exit
    return 0;
    }

调用析构函数不是关于atexit而是exit

我通常不认为std::exit任何好的C++编程。事实上,这和std::atexit

extern "C"   int atexit( void (*func)() ); // in <cstdlib>

来自 C 标准库。从你的例子来看,我相信你已经看到了 http://en.cppreference.com/w/cpp/utility/program/exit,你也看到了

"堆栈没有展开:不调用具有自动存储持续时间的变量析构函数。"

您的问题"为什么"的答案是什么?在某些情况下,特别是未恢复的错误,您可能会使用exit,但通常使用应坚持使用异常,例如,

Static static_variable; 
int mainactual()
{
    Local local_variable; 
    Sample static_variable;
    throw std::exception("EXIT_FAILURE"); // MS specific
    // ... more code
}
int main()
{
    try 
    { 
        mainactual() 
    }catch ( std::exception & e )
    {
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}