Menu ▾ ▴

#12 Certain C++ objects are prematurely destroyed

Current CVS
open
bindings (5)
5
2003-10-07
2003-10-07
No

We had talked about this as a *theoretical* issue --
something that might come up in the course of writing a
program -- but this is the first time that the problem has
actually manifested itself in a "real" program that I'm
working on.

The "big picture": If a Qt# method returns a wrapped object
that Qt# did not create and not does retain a reference to
the wrapped object, the GC may effect the wrapped object,
which in turn triggers deleting the Qt/C++.

A specific case occurs when I create a QTable and attempt
to access its QHorizontalHeader (where the column text is
stored):

table = new QTable( 5, 3, this, "table" );

table.HorizontalHeader().SetLabel( 0,"Last Name" );

When Qt tried to show the dialog box, I got errors like this
(truncated for brevity):

Unhandled Exception: System.NullReferenceException: A
null value was found
where an object instance was required
in (unmanaged) (wrapper managed-to-native)
Qt.QDialog:qt_QDialog_minimumSizeHint (intptr)
in <0x00004> (wrapper managed-to-native)
Qt.QDialog:qt_QDialog_minimumSizeHint

When table.HorizontalHeader() is called, Qt# creates a
managed object to contain the QHeader that Qt returns.
However, because the managed object is never referenced
later in the code, the GC considers is eligible for GC, and
the destructor for QHeader deletes the underlying Qt
object. In other words, as soon as the GC runs, the
horizontal header of the QTable is deleted, which
makes Qt very unhappy.

The work-around so far is to create a private field to
contain the header. (Making a local variable to contain the
QHeader is not a solution. It will still be eligible for garbage
collection.)

Memory management is a difficult issue when mixing
garbage collected environments (i.e. CLR) with
non-garbage collected environments. So far there
have been more problems with objects being freed
prematurely than accidental object retention.

It will probably be necessary to re-think some of the
memory management polices and also to realize that the
policies might not be uniform access all widgets.

Discussion


Log in to post a comment.