I know now that Shared_ptr is thread-safe enougth for my needs and often the best solution but sometimes one wants a more lightweight alternative and I've been using Intrusive_ptr. To make it easier to use I've stolen this class from Beyond the C++ Standard Library by B. Karlsson, If a class inherits it publicly it becomes "intrusive enabled".
class IntrusiveCount { // base class to enable derived class for use with the Boost intrusive smart pointer
public:
virtual ~IntrusiveCount(){}
friend void intrusive_ptr_add_ref(IntrusiveCount* p) {
++p->ref_count;
}
friend void intrusive_ptr_release(IntrusiveCount* p) {
if (--p->ref_count == 0) delete p;
}
protected:
IntrusiveCount() : ref_count(0) {}
IntrusiveCount& operator=(const IntrusiveCount&) {
return *this;
}
private:
IntrusiveCount(const IntrusiveCount&);
short ref_count;
};
The problem with the above class is that its not thread-safe so I've tried to modified it using TBB. I would appreciate if someone could have a look at it and tell me if there's something wrong with my approach.
class IntrusiveCount { // thread-safe base class to enable derived class for use with the Boost intrusive smart pointer
public:
virtual ~IntrusiveCount(){}
friend void intrusive_ptr_add_ref(IntrusiveCount* p) {
p->ref_count.fetch_and_add(1); // increment counter atomically
}
friend void intrusive_ptr_release(IntrusiveCount* p) {
if
(p->ref_count.fetch_and_add(-1) == 1) delete p; // decrement counter. If it was 1 before it's 0 now so delete }
protected:
IntrusiveCount() {ref_count=0;}
IntrusiveCount& operator=(const IntrusiveCount&) {
return *this;
}
private:
IntrusiveCount(const IntrusiveCount&);
tbb::atomic<int> ref_count;
};
I had to change the counter to an int (from short) otherwise I get this level 2 warning on VS2008 standard,
C:UsersadminDocumentsMint bbsrcinclude bbatomic.h(157) : warning C4244: 'argument' :
conversion from 'tbb::internal::atomic_traits<Size,M>::word' to 'short', possible loss of data