[C++-sig] shared_ptr vs. intrusive_ptr

Jeff Webb jeff.webb at nta-inc.net
Tue Jul 22 17:44:16 CEST 2008


Thank you for sharing your thoughts on this, Roman.

Roman Yakovenko wrote:
>> (1) It seems that if you are designing a C++ library from the ground up to
>> use with boost::python, it makes a lot of sense to use smart pointers
>> internally in your C++ library.  Python uses reference counting to manage
>> objects, so if you use reference counting in your C++ library, you are
>> laying the foundation for a seamless python interface instead of fighting
>> Python's memory management.
> 
> No, but if you don't use smart pointers, you will have to pay a lot
> attention to call policies.

By 'no', do you mean that it is *not* a good idea to use smart pointers internally when designing a C++ library to use with boost::python and/or that using smart pointers does *not* make integration with python easier?  By no means am I implying that this is the only good way to do things, but it seems to be a straightforward and reasonable approach, does it not?

> If it is "very similar" to shared_ptr, than you can make it work too:
> http://www.language-binding.net/pyplusplus/troubleshooting_guide/smart_ptrs/smart_ptrs.html

Thanks for providing the examples and documentation.  I will take a closer look at this when I get a chance.

>> (5) Summary:  If you are wrapping a relatively small number of objects or
>> you are wrapping very large objects, the overhead of shared_ptr is probably
>> acceptable.  If you are wrapping a large number of very small objects, then
>> a custom intrusive_ptr solution is worth looking into.
> 
> Not at all. Your memory management should be clear. For example you
> can take a look on Ogre and Python-Ogre library. Ogre has a lot of
> objects passed around but the ownership is very clear.

What does your 'not at all' refer to?  Are you saying that in the situation outlined above, a custom/intrusive_ptr is not even worth considering?  If so, please explain why.  (Again, I am not saying it is the best solution in all cases, but simply that it seems to provide a clean solution to the problem at hand.)

In my limited experience, I have found that even some 'clear' memory management schemes are difficult to cleanly map to python.  It seems that any management scheme where a wrapped object is not owned by python is potentially problematic because the object's owner could delete the wrapped object from C++, leaving an 'empty' python wrapper that is still referenced from python.  I think that using reference counting internally will eliminate this problem.  Of course, reference counting does have memory and execution overhead, so there is a trade off, of course.

Thanks again for your input,

Jeff



More information about the Cplusplus-sig mailing list