[C++-sig] Re: Dangling Reference Exception dramas

David Abrahams dave at boost-consulting.com
Thu May 22 17:13:13 CEST 2003

"Daniel Paull" <dlp at fractaltechnologies.com> writes:

> Hi Dave,
> I've formulated a test case which shows up the problem.  See the listing
> at the end of this post.  Here is what is happening:
> 1) There is a class Foo which is being exposed to Python with the
> intention of being subclassed.
> 2) A subclass of Foo is passed from Python to C++ via the setFoo()
> method.  In my real case this is registry of objects, not just a global
> pointer.
> 3) The getBar() method is called on the Foo returned in (2)
> The code as listed below produces the following output:
>     Foo()
>     Got the Foo object
>     hello: <__main__.MyFoo object at 0x0032DDC8>
>     ReferenceError: Attempt to return dangling pointer to object of
> type: class Bar
>     ~Foo()
> If you uncomment the line "self.bar_extra_ref = self.bar" in MyFoo's
> __init__ method, you get the following output:
>     Foo()
>     Got the Foo object
>     hello: <__main__.MyFoo object at 0x009426F0>
>     ~Foo()
> This shows that introducing one extra reference to the Bar object stops
> the exception from being signalled, hence, the reference count of
> self.bar must be 2 in the original listing (as getBar() returns).  It
> was this observation that made me think that the "<= 2" check noted in
> my original post may be in error.

You're right!  Thanks for locating this bug.

In fact, there were tests attempting to check for this, but details
of the way the tests were working, and other code in the system,
conspired to hide the issue.

Your patch was not sufficient to fix it, though.  Before submitting a
patch, it's best if you run all the regression tests first.  The
"callbacks" test fails if we just change "<= 2" to "< 2".

I'll be checking in a fix momentarily.
Dave Abrahams
Boost Consulting

More information about the Cplusplus-sig mailing list