开发者

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

boost::intrusive_ptr requires int开发者_JAVA百科rusive_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.


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


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


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 ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜