Boost logo

Boost :

From: Ulrich Eckhardt (doomster_at_[hidden])
Date: 2006-04-10 12:05:21

On Thursday 06 April 2006 07:50, I wrote:
> says:
> "As a general rule, if it isn't obvious whether intrusive_ptr better
> fits your needs than shared_ptr, try a shared_ptr-based design first."
> I wonder why? Embedding the refcounter into the object seems to me much
> more natural and performant than adding another free-store allocation which
> shared_ptr requires.

Nobody wants to even take a guess why? I seriously don't know why one would
use shared_ptr by default - I'm aware that some people might want the
additional features, but that doesn't justify such an advise.

> Another related thing is why is there no complementary class to add a
> refcounter to an object? Something like
[snipped code]

Okay, I tried it now, and propose this here as enhancement for intrinsic
pointer. What do you think?


#include <iostream>
#include <ostream>
#include <boost/intrusive_ptr.hpp>

namespace boost {
template<typename ObjectType>
class intrusive_refcount
    // not copyable
    intrusive_refcount( intrusive_refcount const& rhs);
    // not assignable
    intrusive_refcount& operator=( intrusive_refcount const& rhs);
public:// protected?
    intrusive_refcount(): refs(0) {}
    ~intrusive_refcount() { assert(refs==0); }
// private with friend?
    void add_ref() { ++refs; }
    void release() { if(!--refs) delete static_cast<ObjectType*>(this); }
    size_t refs;

template<typename T>
void intrusive_ptr_add_ref(intrusive_refcount<T>* ptr)

template<typename T>
void intrusive_ptr_release(intrusive_refcount<T>* ptr)
}// end of namespace boost

struct foo: boost::intrusive_refcount<foo>
    { std::cout << "foo::foo()\n"; }
    foo( foo const& )
    { std::cout << "foo::foo( foo const&)\n"; }
    foo& operator=( foo const& )
    { std::cout << "foo& foo::operator=( foo const&)\n"; return *this; }
    { std::cout << "foo::~foo()\n"; }

int main()
    boost::intrusive_ptr<foo> ptr1( new foo);

    boost::intrusive_ptr<foo> ptr2;
    ptr2 = ptr1;

Boost list run by bdawes at, gregod at, cpdaniel at, john at