小编efa*_*bor的帖子

即使使用智能指针,C++也会在异常情况下泄漏

我是智能指针世界的新手.我已经完成了我的阅读,并且所有人都表示即使程序在遇到异常后退出,智能指针也会避免泄漏内存.

我写了一个简单的程序试试这个,但Valgrind告诉我我的程序泄漏了内存(三个分配,只有一个免费).

这是源代码:

#include <iostream>
#include <memory>

using namespace std;

int main()
{
    auto_ptr<int> ptr_int(new int(5));

    throw std::bad_alloc();

    cout << *ptr_int;
}
Run Code Online (Sandbox Code Playgroud)

这个Valgrind的报告:

==27862== Memcheck, a memory error detector
==27862== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==27862== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==27862== Command: ./smart_pointers
==27862== Parent PID: 5388
==27862==
==27862==
==27862== HEAP SUMMARY:
==27862==     in use at exit: 104 bytes in 2 blocks
==27862==   total heap usage: …
Run Code Online (Sandbox Code Playgroud)

c++ memory-leaks smart-pointers

9
推荐指数
2
解决办法
1260
查看次数

标签 统计

c++ ×1

memory-leaks ×1

smart-pointers ×1