Is there a way to increase the efficiency of shared_ptr by storing the reference count inside the controlled object?

前端 未结 4 1918
有刺的猬
有刺的猬 2021-01-20 19:15

This is becoming a common pattern in my code, for when I need to manage an object that needs to be noncopyable because either A. it is \"heavy\" or B. it is an operating sys

4条回答
  •  北海茫月
    2021-01-20 20:02

    Use a boost::intrusive_ptr which is designed to work on a class with an embedded reference count.

    Non-tested example based on example here:

    class Resource; 
    
    class Implementation : public boost::noncopyable 
    { 
        friend class Resource;
        HANDLE someData;
        int refCount; // The reference count.
        Implementation(HANDLE input) : someData(input) { refCount = 0; }; 
        void SomeMethodThatActsOnHandle() { 
            //Do stuff 
        }; 
    public: 
        ~Implementation() { FreeHandle(someData) }; 
    };
    
    intrusive_ptr_add_ref(Implementation* imp) { imp->refCount++; }
    intrusive_ptr_release(Implementation* imp) { if(--imp->refCount) == 0) delete imp; }
    
    class Resource 
    { 
        boost::intrusive_ptr impl; 
    public: 
        Resource(int argA) explicit { 
            HANDLE handle =  
                SomeLegacyCApiThatMakesSomething(argA); 
            if (handle == INVALID_HANDLE_VALUE) 
                throw SomeTypeOfException(); 
            impl.reset(new Implementation(handle)); 
        }; 
        void SomeMethodThatActsOnTheResource() { 
            impl->SomeMethodThatActsOnTheHandle(); 
        }; 
    }; 
    

提交回复
热议问题