是否保证在发生异常时释放由智能指针管理的已分配内存,如下所示?
#include <memory>
void test( std::shared_ptr<int> sptr )
{
throw "exception";
}
int main()
{
std::shared_ptr<int> ptr( new int(1) );
test( ptr );
return 0;
}
我尝试执行代码,在 shared_ptr
析构函数中放置断点,但我没有看到它被调用。我认为内存应该自己清理。我是对的,还是不会清理干净?
最佳答案
语言标准规定:
If no matching handler is found, the function
std::terminate()
is called; whether or not the stack is unwound before this call tostd::terminate()
is implementation-defined
因此不能保证您的程序会自行清理,但大多数(如果不是全部)现代操作系统都会在事后进行清理。
如果您捕获了异常,shared_ptr
的实例将被正确销毁,确保没有泄漏。
关于c++ - 下面的 C++ shared_ptr 用法会不会有任何泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40858323/