当我们使用 atexit() 时,不会为本地对象调用析构函数
Destructor not called for local objects when we use atexit()
请帮忙:我知道析构函数和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;
}
相关文章:
- 什么时候调用组成单元对象的析构函数
- 使用基类指针创建对象时,缺少派生类析构函数
- 对具有动态分配的内存和析构函数的类对象的引用
- C++析构函数调用两次,堆栈分配的复合对象
- 如何从 Gtk::窗口调用派生对象的析构函数
- 为什么数组中对象的析构函数在被另一个对象替换时不被调用?
- 为什么为未删除的对象调用析构函数?
- 对象的构造函数和析构函数
- 循环中本地对象的析构函数是否保证在下一次迭代之前被调用?
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- 从未调用shared_ptr对象的析构函数
- 是否可以在其析构函数中使用指向已销毁对象的指针?
- 使用私有析构函数删除动态分配的对象
- C++ std::线程调用方法,从对象原因到调用此类的析构函数
- 为什么在这里调用析构函数,以及在调用该对象析构函数后如何调用对象成员函数?
- 对象析构函数在多线程处理时不断被调用,但该对象并未超出范围
- C++包含包含指针的对象的对象析构函数
- Objective-C++C++对象析构函数
- 结构对象析构函数
- 在Exit()时调用基本对象析构函数