Boost logo

Boost Users :

From: Alexander Gutenev (gutenev_at_[hidden])
Date: 2008-07-30 16:03:06


Hello.

I want to use intrusive_ptr as a smart pointer to have reference counting
without shared_ptr overhead. There's no implementation for embedding
reference counting into a pointee class provided by Boost.Smart Ptr library.
I'd like to have reference counting easily embedded, like thru inheritance:

class test
  : public intrusive_pointee_base<test>
{
...
};

I come to an implementation of this. As i'm sure this was coded many times
before, two questions: (1) Why stock implementation of intrusive counter is
not included to Smart Pointers library ? (2) Is there something wrong with
my code ?

struct refcount
{
  refcount(void) : count_(0) {}
  refcount(refcount const&) : count_(0) {}
  refcount& operator=(refcount const&) {}
  long operator++(void) { return ::InterlockedIncrement(&count_); }
  long operator--(void) { return ::InterlockedDecrement(&count_); }
private:
  mutable volatile long count_;
};

template<class T>
void intrusive_ptr_add_ref(T * p);

template<class T>
void intrusive_ptr_release(T * p);

template<class Derived>
class intrusive_pointee_base
{
  friend void intrusive_ptr_add_ref<Derived>(Derived * p);
  friend void intrusive_ptr_release<Derived>(Derived * p);
  refcount reference_counter_;
protected:
  ~intrusive_pointee_base(void) {}
};

template<class T>
void intrusive_ptr_add_ref(T * p)
{
  intrusive_pointee_base<T> * pbase = p;
  ++(pbase->reference_counter_);
}

template<class T>
void intrusive_ptr_release(T * p)
{
  intrusive_pointee_base<T> * pbase = p;
  if (!--(pbase->reference_counter_))
    delete p;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net