Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

intrusive_ptr: Why isn't a common base class provided?

boost::intrusive_ptr requires intrusive_ptr_add_ref and intrusive_ptr_release to be defined. Why isn't a base class provided which will do this? There is an example here: http://lists.boost.org/Archives/boost/2004/06/66957.php, but the poster says "I don't necessarily think this is a good idea". Why not?

Update: I don't think the fact that this class could be misused with Multiple Inheritance is reason enough. Any class which derives from multiple base classes with their own reference count would have the same issue. Whether these refcounts are implemented via a base class or not makes no difference.

I don't think there's any issue with multithreading; boost::shared_ptr offers atomic reference counting and this class could too.

like image 415
Jon Avatar asked May 25 '10 08:05

Jon


3 Answers

Boost provides a facility for that. It can be configured for either thread-safe or thread-unsafe refcounting:

#include <boost/intrusive_ptr.hpp>
#include <boost/smart_ptr/intrusive_ref_counter.hpp>

class CMyClass
    : public boost::intrusive_ref_counter<
                               CMyClass,
                               boost::thread_unsafe_counter>
     ...

boost::intrusive_ptr<CMyClass> myPtr;

http://www.boost.org/doc/libs/1_62_0/libs/smart_ptr/intrusive_ref_counter.html

like image 146
Boris Glick Avatar answered Nov 07 '22 08:11

Boris Glick


It's so you can use intrusive_ptr with classes that already implement add and release.

like image 30
Chris Card Avatar answered Nov 07 '22 09:11

Chris Card


The problem would be with Multiple Inheritance. If you inherit from 2 objects implementing this base, then you have 2 counters for your single object... and that could cause havoc.

Thus you would need to make the ptr_add and ptr_release methods virtual, so that the derived class may implement an override to properly synchronize the multiple counters at once... Some performance penalty here, especially since most of the times it would be completely unnecessary (there would be no override) because it's only useful for Multiple Inheritance after all.

And of course in Multi-Threaded environments you could have (for short periods of time) desynchronized counters (the first was incremented but the thread was interrupted before the second was) I can't think yet of any problem it may cause, but it's not a sane situation.

You also add clutter to the class, some clients may not need reference counting after all (if they create the object on the stack).

I think it's not a good idea ;)

like image 27
Matthieu M. Avatar answered Nov 07 '22 08:11

Matthieu M.