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

廉价感情. 提交于 2019-12-10 03:15:07

问题


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.


回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/2903179/intrusive-ptr-why-isnt-a-common-base-class-provided

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!