[C++-sig] re: how to wrap this handle/body design?

David Abrahams dave at boost-consulting.com
Wed Mar 5 03:23:13 CET 2003


Wow, not even emacs was able to clean up the crazy line breaks in
your message; I had to do this by hand...

"FLETCHER, Shayne, FM" <Shayne.FLETCHER at rbos.com> writes:

> Dave:
>
> 		>> Apologies in advance for the length of the post. I have
> 		>> been trying to work out the details of how to reflect a
> 		>> handle/body with a clone semantics type design but am
> 		>> running in to diffuculties...
>
> 	>Well, I think I am able to understand the basic nature of your
> 	>problem, but it would sure have helped if you had reduced it to a
> 	>much smaller case.  I think that's possible for you to do fairly
> 	>easily and it would probably deepen your understanding of the
> 	>problem as well.
>
> Yes. Apologies for that... I am very keen to get to grips with the
> problem in it's entirety.
>
> 		>> The basic problem is 'dangling references':
>
> 	>OK, do you understand what that means?

> 	>The Python implementation of the virtual function is returning a
> 	>new Python object which owns the object whose address you're
> 	>trying to return.  The inside of your virtual function overload
> 	>contains the only reference to that new object.  If the function
> 	>returns the reference count will be decremented, the object will
> 	>be destroyed, and the resulting pointer will dangle.
>
> Indeed, I have got this. What has eluded me thus far (beyond
> artifically bumping up the PyObject's ref count) is how to avoid the
> situation.

"Don't try to return references to objects you own" is the basic
approach.  It's the same rule as you'd use for C++. IOW, you don't do
this:

        X& f()
        {
            X x;
            return x;
        };

> 	> There are several ways to approach this problem, and they all
> 	> involve using smart pointers.
>
> Can you point me at any documentation relating to these approaches?

Sadly, no.  However, if you take my advice about recasting the
interface in terms of smart pointers, then you can return a
smart pointer instead of a reference in this case.

> 	> I would strongly recommend that you recast your interface in
> 	>terms of smart pointers anyway; it will help in so many ways.
> 	>So:
>

HTH again,
-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list