以下代码会导致资源泄漏吗?

时间:2015-10-07 22:12:23

标签: c++

class Base {
public:
    Base(int i1, int i2): ip1{new int(i1)}{
        try {
            ip2 = new int(i2);
        } catch (std::bad_alloc& ){
            delete ip1;
        }
    }
    ~Base() { delete ip1; delete ip2; }
private:
    int *ip1, *ip2;
};

class Derived: public Base {
public:
    Derived(int i1, int i2, int i3): Base(i1, i2), ip3(new int(i3)) {}
    ~Derived() { delete ip3; }
private:
    int *ip3;
};

我不在Derived构造函数中使用 try-catch 。我想知道如果 ip3(new int(i3))抛出异常,ip1和ip2分配的内存是否会被删除?

1 个答案:

答案 0 :(得分:4)

是的,但只需使用unique_ptrmake_unique来表示所有这些指针,就可以轻松完成同样的事情。