intrusive_ptr: Why isn't a common base class p

2019-04-24 01:44发布

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.

3条回答
可以哭但决不认输i
2楼-- · 2019-04-24 02:29

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

查看更多
Fickle 薄情
3楼-- · 2019-04-24 02:32

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

查看更多
时光不老,我们不散
4楼-- · 2019-04-24 02:48

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

查看更多
登录 后发表回答