簡體   English   中英

以下代碼會導致資源泄漏?

[英]will following code cause resource leak?

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;
};

我不在派生構造函數中使用try-catch 我想知道ip3(new int(i3))是否拋出異常,是否會刪除ip1和ip2分配的內存?

是的,但是通過對所有這些指針使用unique_ptrmake_unique ,可以使同一件事變得容易得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM