简体   繁体   English

智能指针如何知道何时在程序崩溃时释放资源?

[英]How do smart pointers know when to free the resources on program crash?

当程序崩溃时,使用诸如unique_ptr之类的智能指针的c ++项目如何知道释放资源?

If the program crashes "gracefully" due to a handled exception, the stack unwinding will call the destructors on any smart pointers and free the memory. 如果程序由于处理的异常而“正常”崩溃,则堆栈展开将在任何智能指针上调用析构函数并释放内存。

For complete crashes (eg segmentation fault, call to std::terminate() ), it is the operating system that will free any memory and resources held by the program. 对于完全崩溃(例如,分段错误,调用std::terminate() ),正是操作系统将释放程序所拥有的任何内存和资源。

When a C++ program crashes, it exits. 当C ++程序崩溃时,它退出。 The operating system cleans up any OS resources it may have asked for, which includes memory, but also other resources (file handles for example). 操作系统会清理它可能要求的所有OS资源,包括内存和其他资源(例如文件句柄)。

Thus, C++ does not clean up - the operating system does. 因此,C ++无法清除-操作系统可以清除。 What once was the C++ heap is returned to the operating system as free memory. 曾经是C ++堆的东西作为空闲内存返回到操作系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM