How to release pointer from boost::shared_ptr?

后端 未结 14 1636
刺人心
刺人心 2020-11-30 06:42

Can boost::shared_ptr release the stored pointer without deleting it?

I can see no release function exists in the documentation, also in the FAQ is explained why it

14条回答
  •  情书的邮戳
    2020-11-30 06:52

    Kids, don't do this at home:

    // set smarty to point to nothing
    // returns old(smarty.get())
    // caller is responsible for the returned pointer (careful)
    template 
    T* release (shared_ptr& smarty) {
        // sanity check:
        assert (smarty.unique());
        // only one owner (please don't play games with weak_ptr in another thread)
        // would want to check the total count (shared+weak) here
    
        // save the pointer:
        T *raw = &*smarty;
        // at this point smarty owns raw, can't return it
    
        try {
            // an exception here would be quite unpleasant
    
            // now smash smarty:
            new (&smarty) shared_ptr ();
            // REALLY: don't do it!
            // the behaviour is not defined!
            // in practice: at least a memory leak!
        } catch (...) {
            // there is no shared_ptr in smarty zombie now
            // can't fix it at this point:
            // the only fix would be to retry, and it would probably throw again
            // sorry, can't do anything
            abort ();
        }
        // smarty is a fresh shared_ptr that doesn't own raw
    
        // at this point, nobody owns raw, can return it
        return raw;
    }
    

    Now, is there a way to check if total count of owners for the ref count is > 1?

提交回复
热议问题