C ++中的内存泄漏示例(通过使用异常) [英] Example of memory leak in c++ (by use of exceptions)

查看:105
本文介绍了C ++中的内存泄漏示例(通过使用异常)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++如何编程有一段写着:

一种常见的编程做法是分配动态内存,分配地址 该内存指向一个指针,使用该指针操作该内存并释放该内存. 当不再需要内存时,使用删除将其删除.如果之后发生异常 成功分配内存,但在执行delete语句之前,内存泄漏 可能发生. C ++标准在标头中提供了类模板unique_ptr 处理这种情况.

A common programming practice is to allocate dynamic memory, assign the address of that memory to a pointer, use the pointer to manipulate the memory and deallocate the memory with delete when the memory is no longer needed. If an exception occurs after successful memory allocation but before the delete statement executes, a memory leak could occur. The C++ standard provides class template unique_ptr in header to deal with this situation.

任何人都可以向我介绍一个发生异常和内存泄漏的真实示例

Any on could introduce me a real example that exception occur and memory will leak like this post?

推荐答案

class MyClass
{
public:
    char* buffer;
    MyClass(bool throwException)
    {
        buffer = new char[1024];
        if(throwException)
            throw std::runtime_error("MyClass::MyClass() failed");
    }

    ~MyClass()
    {
        delete[] buffer;
    }
};


int main()
{
    // Memory leak, if an exception is thrown before a delete
    MyClass* ptr = new MyClass(false);
    throw std::runtime_error("<any error>");
    delete ptr;
}


int main()
{
    // Memory leak due to a missing call to MyClass()::~MyClass()
    // in case MyClass()::MyClass() throws an exception.
    MyClass instance = MyClass(true);
}

另请参见: C ++:如果构造函数可能抛出异常,则处理资源(参考常见问题解答17.4]

这篇关于C ++中的内存泄漏示例(通过使用异常)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆