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

来源:互联网 发布:免费领取比特币软件 编辑:程序博客网 时间:2024/04/30 22:35

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

原创粉丝点击