Manually incrementing and decrementing a boost::shared_ptr?

前端 未结 7 1447
后悔当初
后悔当初 2021-01-05 22:57

Is there a way to manually increment and decrement the count of a shared_ptr in C++?

The problem that I am trying to solve is as follows. I am writing a library in C

7条回答
  •  失恋的感觉
    2021-01-05 23:42

    I came across a use case where I did need something like this, related to IOCompletionPorts and concurrency concerns. The hacky but standards compliant method is to lawyer it as described by Herb Sutter here.

    The following code snippet is for std::shared_ptr as implemented by VC11:

    Impl File:

    namespace {
        struct HackClass {
            std::_Ref_count_base *_extracted;
        };
    }
    
    template<>
    template<>
    void std::_Ptr_base<[YourType]>::_Reset(std::auto_ptr &&h) {
         h->_extracted = _Rep; // Reference counter pointer
    }
    
    std::_Ref_count_base *get_ref_counter(const std::shared_ptr<[YourType]> &p) {
         HackClass hck;
         std::auto_ptr aHck(&hck);
    
         const_cast&>(p)._Reset(std::move(aHck));
    
         auto ret = hck._extracted; // The ref counter for the shared pointer
                                    // passed in to the function
    
         aHck.release(); // We don't want the auto_ptr to call delete because
                         // the pointer that it is owning was initialized on the stack
    
         return ret;
    }
    
    void increment_shared_count(std::shared_ptr<[YourType]> &sp) {
         get_ref_counter(sp)->_Incref();
    }
    
    void decrement_shared_count(std::shared_ptr<[YourType]> &sp) {
         get_ref_counter(sp)->_Decref();
    }
    

    Replace [YourType] with the type of object you need to modify the count on. It is important to note that this is pretty hacky, and uses platform specific object names. The amount of work you have to go through to get this functionality is probably indicative of how bad of an idea it is. Also, I am playing games with the auto_ptr because the function I am hijacking from shared_ptr takes in an auto_ptr.

提交回复
热议问题