当前位置:  开发笔记 > 编程语言 > 正文

异常抛出时避免内存泄漏的方法

如何解决《异常抛出时避免内存泄漏的方法》经验,为你挑选了0个好方法。

这是C++ Primer第18章的练习:

void exercise(int *b, int *e)
{
    vector v(b, e);
    int *p = new int[v.size()];
    ifstream in("ints");
    // exception occurs here
}

上面的代码会导致内存泄漏,因为我们直接管理的内存(即p)在发生异常时不会自动释放.

练习18.3:

如果抛出异常,有两种方法可以使前面的代码正常工作.描述它们并实施它们.

我知道我们可以使用智能指针来避免这个陷阱:

void exercise(int *b, int *e)
{
    vector v(b, e);
    unique_ptr p(new int[v.size()]);
    ifstream in("ints");
    // exception occurs here
}

要么:

void exercise(int *b, int *e)
{
    vector v(b, e);
    shared_ptr p(new int[v.size()], [](int *p){ delete[] p; });
    ifstream in("ints");
    // exception occurs here
}

我不确定这些是不是TWO.毕竟,它们实际上是相同的.所以我想到了另一种方式:

void exercise(int *b, int *e)
{
    vector v(b, e);
    int *p = new int[v.size()];
    ifstream in("ints");
    // exception occurs here
    if(!in)
        throw p;
}

// caller
try {
    exercise(b, e);
} catch (int *err) {
    delete[] err; // initialize err with b and delete e.
}

如果发生异常,则抛出p初始化另一个指针并删除该指针.我知道这不是一个完美的解决方案,因为可能会发生其他异常,所以我甚至没有机会抛出p.但我想不出更好的一个.你能帮忙找到第二种方式吗?

推荐阅读
周扒pi
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有