on Sun Apr 22 2012, Holger Brandsmeier <brandsmeier-AT-gmx.de> wrote:
> Dear list,
>
> how is it possible to have a class in C++ that can be extended from
> python and that stores a weak_ptr to itself?
Easy, I think: just like any other class you wrap. Are you aware of
boost::enable_shared_from_this? It does all of that internally.
> The reason why I want to do this:
> - using a weak_ptr to itself does not introduce a memory leak.
> - from a C++-member of that class I can call other functions that
> expect a shared_ptr<>, in that case I convert the weak_ptr to a
> shared_ptr and all the memory management works nicely.
>
> The way I would suspect this to work is:
> struct I {
> void setThisRCP(boost::shared_ptr<I> ptr) {
> thisRCP = ptr;
> }
>
> boost::shared_ptr<I> getThisRCP() const {
> return thisRCP.lock();
> }
>
> boost::weak_ptr<I> thisRCP;
> };
>
> Then I export this class to C++ and in python I would do:
> class IDer(I):
> def __init__(self):
> I.__init__(self)
> self.setThisRCP(self)
>
> And I would suspect that I can use that class now in C++ and in
> particular calling getThisRCP() from C++ returns a valid shared
> pointer. However, immediately after the call of
> `self.setThisRCP(self)` the weak_ptr is already invalid and getThisRCP
> returns an shared pointer to Null (None in python).
If you use boost::shared_ptr<I> as the Holder for your wrapper, you'll
be able to do that conversion. I see you've done that with "J" in your
example, but not with "I". Why not?
If you use enable_shared_from_this, the internal weak_ptr will be
initialized from the first shared_ptr that is constructed to manage the
object. Everything should work.
--
Dave Abrahams
BoostPro Computing
http://www.boostpro.com
_______________________________________________
Cplusplus-sig mailing list
[email protected]
http://mail.python.org/mailman/listinfo/cplusplus-sig