
On Thursday 06 April 2006 07:50, I wrote:
http://boost.org/libs/smart_ptr/intrusive_ptr.html 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? Uli #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); } private: size_t refs; }; template<typename T> void intrusive_ptr_add_ref(intrusive_refcount<T>* ptr) { ptr->add_ref(); } template<typename T> void intrusive_ptr_release(intrusive_refcount<T>* ptr) { ptr->release(); } }// end of namespace boost struct foo: boost::intrusive_refcount<foo> { 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; } ~foo() { std::cout << "foo::~foo()\n"; } }; int main() { boost::intrusive_ptr<foo> ptr1( new foo); boost::intrusive_ptr<foo> ptr2; ptr2 = ptr1; }