[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Best way to manage refs in C + Garbage collection in a single collectgarbage() call.
- From: "Mauro Iazzi" <mauro.iazzi@...>
- Date: Thu, 24 Jul 2008 15:50:33 +0200
I had the same problem using Qt. I solved it using the environment to
store a method which is called by __gc on collection. It is that
method that contains the destructor if needed. With some __newindex
work you can
widget.__gc = widget.delete -- take ownership of widget
widget.__gc = nil -- don't destruct if collected
different functions could do this automatically. In your case
addWidget would release.
This assumes you don't actually need to also track the instances. In
the Qt case I have wrappers around functions that return children.
For the other problem, since I just used a userdata containing a
pointer, the destructor just zeroes this. Other functions will see
that as a NULL pointer. If you are wrapping some API you should add
the check to the wrappers. The gc will collect when it is more
appropriate without interfering with destructors.
2008/7/24 Michael Ferenduros <email@example.com>:
> I guess you need to make the relationship a more explicit to the GC. Maybe
> storing a table of all member-widgets in the container's env-table would do
> the trick.
> You could alternatively do something equivalent with a semi-weak table
> stashed away in the registry (but possibly not if a widget can belong to
> multiple containers).
>> So, two questions arise:
>> 1) Is there a better way to manage refs in C++ than the way I'm doing it?
>> 2) Is there a way to do this so that everything gets collected in the same
>> call to collectgarbage()?