微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

即使使用智能指针,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;
}

这个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: 3 allocs,1 frees,120 bytes allocated
==27862==
==27862== 4 bytes in 1 blocks are still reachable in loss record 1 of 2
==27862==    at 0x4026351: operator new(unsigned int) (vg_replace_malloc.c:255)
==27862==    by 0x804878A: main (smart_pointers.cpp:8)
==27862==
==27862== 100 bytes in 1 blocks are possibly lost in loss record 2 of 2
==27862==    at 0x4025BD3: malloc (vg_replace_malloc.c:236)
==27862==    by 0x40E861A: __cxa_allocate_exception (in /usr/lib/libstdc++.so.6.0.14)
==27862==    by 0x80487AE: main (smart_pointers.cpp:10)
==27862==
==27862== LEAK SUMMARY:
==27862==    definitely lost: 0 bytes in 0 blocks
==27862==    indirectly lost: 0 bytes in 0 blocks
==27862==      possibly lost: 100 bytes in 1 blocks
==27862==    still reachable: 4 bytes in 1 blocks
==27862==         suppressed: 0 bytes in 0 blocks
==27862==
==27862== For counts of detected and suppressed errors,rerun with: -v
==27862== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 19 from 8)

使用智能指针确保分配的资源将被破坏,即使出现异常?

解决方法

调用 std::terminate()(如未捕获的异常情况)时,正常的清理不会运行(至少对于main()的堆栈帧),因此您在堆栈帧中分配的内存泄漏,甚至虽然它应该由智能指针来管理.当你在main()中捕获std :: bad_alloc,并且返回正常时,智能指针就可以做到这一点了.

原文地址:https://www.jb51.cc/c/111680.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐