Pay close attention to manage multiple resource in one object - C++11, 24 of n

本文探讨了C++中构造函数与析构函数执行期间可能遇到的问题,特别是当构造函数抛出异常时如何避免内存泄漏。通过示例展示了两种解决方法:使用智能指针管理和委托构造函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Caveats:
  • if constructor (at any point, say in the body of constructor) throws, the object's desctructor will NEVER be invoked, because the compiler can't tell what's the state of the object under construction like.
  • If constructor throws, all of the fully constructed base subobjects and data members will be destructed.
  • C++11, if the non-delegating constructor for an object has completed execution and a delegating constructor for that object exists with an exception, the object's destructor will be invoked.
  • Example:
    class MayLeak {
    public:
        MayLeak(int x, int y): a_(nullptr), b_(nullptr) {
            a_ = new A(x); 
            b_ = new B(y);  // if new B(y) throws, a_ is leaked
        }
        ~MayLeak() {
             delete b_;
             delete a_;
        }

    private:
        A a_;
        B b_;
    };

    Preferred fix:
    class MayLeak {
    public:
        MayLeak(): a_(make_shared<A>(x)), b_(make_shared<B>(y)) {
            // if make_unique<B>() throws, a_ is also desctructed, no leak
        }

    private:
        shared_ptr<A> a_;
        shared_ptr<B> b_;
    };

    Another fix in C++11:
    class MayLeak {
    public:
        MayLeak() :  a_(nullptr), b_(nullptr)  {
        }

        MayLeak(int x, int y): MayLeak() {
            // When non-delegating MayLeak() constructor finishes,
            // ~MayLeak destructor will be guaranteed to be invoked by stanadard
            a_ = new A(x); 
            b_ = new B(y);  // if new B(y) throws, a_ is NOT leaked, because ~MayLeak will be invoked.
        }
        ~MayLeak() {
             delete b_;
             delete a_;
        }

    private:
        A *a_;
        B *b_;
    };

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值