【问题标题】:Destructor not called for local objects when we use atexit()当我们使用 atexit() 时,没有为本地对象调用析构函数
【发布时间】:2016-05-16 22:04:26
【问题描述】:

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

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

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

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

提前致谢:

class Static {
public:
    ~Static() 
        {
        std::cout << "Static dtor\n";
        }
    };
class Sample {
public:
    ~Sample() 
        {
        std::cout << "Sample dtor\n";
        }
    };

class Local {
public:
    ~Local() 
        {
        std::cout << "Local dtor\n";
        }
    };

Static static_variable; // dtor of this object *will* be called
void atexit_handler()
    {
    std::cout << "atexit handler\n";
    }
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;
    }

【问题讨论】:

  • 当您调用 exit 时,这些变量仍在范围内,当然,exit 不会返回。那么析构函数什么时候可以运行呢?

标签: c++ destructor atexit


【解决方案1】:

调用析构函数不是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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 2018-10-26
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    相关资源
    最近更新 更多