c++ - 下面的 C++ shared_ptr 用法会不会有任何泄漏?

标签 c++ c++11 smart-pointers

是否保证在发生异常时释放由智能指针管理的已分配内存,如下所示?

#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 to std::terminate() is implementation-defined

因此不能保证您的程序会自行清理,但大多数(如果不是全部)现代操作系统都会在事后进行清理。

如果您捕获了异常,shared_ptr 的实例将被正确销毁,确保没有泄漏。

关于c++ - 下面的 C++ shared_ptr 用法会不会有任何泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40858323/

相关文章:

c++ - C++-重载结构取消引用运算符,并在unique_ptr中使用它

c# - 像 c++ 中的 c# 参数一样吗?

c++ - 如何初始化这个填充有&functionA, &functionB 的数组?

c++ - move 构造函数(和其他)的正确实现是什么?

c++ - 双指针函数参数和 CComPtr

C++11 make_shared 实例化

c++ - C/C++ 表达式运算符优先级的括号计算器

c++ - C++ 中的 MATLAB 张量索引

c++ - 如何使用 isnan 作为 std::find_if 的谓词函数 (c++11)

c++ - 此示例中 cppreference 中的任务是什么?