dimanche 28 février 2016

Enable shared ownership support for an object

I enabled a simple shared ownership for a class with the following control block structure

struct Ptr
{
    C* value_ ;
    size_t ref_ ;
    IdType id_ ;
} ;

Ptr* ptr_ ;

value_ is the payload with a shared ownership,

id_ is a database Id that links value to a database row. It can exist with or without a payload, that's why it's not part of the payload but part of the control block,

ref_ is the reference counter.

And the following functions allowing to take ownership and releasing it:

template<class C>
void ptr<C>::free()
{
    if(ptr_)
    {
        ptr_->ref_-- ;
        if(ptr_->ref_==0)
        {
            delete ptr_->value_ ;
            delete ptr_ ;
            ptr_ = nullptr ;
        }
    }
}

template<class C>
void ptr<C>::take()
{
    if(ptr_)
        ptr_->ref_++ ;
}

This works well but I need to go further as it does not cover my needs:

  1. This is not conform to the shared_ptr standard as my control block is not thread safe and my ownership manipulation is not atomic
  2. I need to add weak ownership support. This will be quite easy as I just need to have a second counter and delete the control block only if all counters falls to 0.

My needs for the ownership behavior are already covered by c++11 smart pointers but they are not designed to be inherited and there is no way to customize the control block.

I tried to understand how the atomicity was handled with both boost and standard library but this is relatively cryptic for now.

So the question is simple, is there a way with boost or stl to enable shared ownership support inside object core design, and by this way be compliant with c++ standards?

Aucun commentaire:

Enregistrer un commentaire