Manually incrementing and decrementing a boost::shared_ptr?

前端 未结 7 1452
后悔当初
后悔当初 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:37

    Another option would be to just allocate dynamically a copy of the shared_ptr, in order to increment the refcount, and deallocate it in order to decrement it. This guarantees that my shared object will not be destroyed while in use by the C api client.

    In the following code snippet, I use increment() and decrement() in order to control a shared_ptr. For the simplicity of this example, I store the initial shared_ptr in a global variable.

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    typedef boost::shared_ptr MySharedPtr;
    MySharedPtr ptr = boost::make_shared(123);
    
    void* increment()
    {
        // copy constructor called
        return new MySharedPtr(ptr);
    }
    
    void decrement( void* x)
    {
        boost::scoped_ptr< MySharedPtr > myPtr( reinterpret_cast< MySharedPtr* >(x) );
    }
    
    int main()
    {
        cout << ptr.use_count() << endl;
        void* x = increment();
        cout << ptr.use_count() << endl;
        decrement(x);
        cout << ptr.use_count() << endl;
    
        return 0;
    }
    

    Output:

    1
    2
    1

提交回复
热议问题