[Interest] QJSEngine leaking memory from QObjects until eval() is complete

Andrew Mulbrook andrew at textux.com
Tue Sep 29 23:13:03 CEST 2015


I'm toying with an application that uses QJSEngine to perform queries and
build reports. Mostly, I was curious how well JavaScript + QObjects would
be up to the job. So far, it's been going great.

However, I ran into a small hurdle today. It appears that QJSEngine when
garbage collecting QObject's will delete the object with deleteLater()
instead of deleting the object outright. I developed a couple work-arounds,
but was curious as to implications:

For example:

/* Equivalent in my JS file */
while ( resourceNotFound )
{
   resource = factory.getHeavyWeightResource(); /* Create big QObject */
   if (checkRightResource(resource))
   {
       return resource;
   }

   /* gc(); <--- Solution 1: manually added to kill 'leak' */
   /* deleteQObject(resource); <---- Solution 2: force immediate deletion */
   /* delete resource; <--- Does not work, deleteLater() */
   /* do nothing, does not work deleteLater(), destructor called after
eval() */
}

Solution 1:
The gc function was simple -

        /* Contents of gc */
        QCoreApplication::processEvents();
        QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);

Solution 2:
The deleteQObject(QObject*) simply calls delete on the passed QObject
       /* Contents of deleteQObject */
       delete obj;

Experimentally, both solutions "work".

Questions: (sorry for length of setup)
  1. Is it a happy accident that Solution 2 seems to properly invalidate
resource in the JS or can I count on that for design? I don't seen an
explicit green-light in documentation.
  2.  Is Solution 1 safe if I control the context of the eval() statement
to a top level main loop function?
  3. Is there some way to get QJSEngine to simply NOT defer deleting
objects that I'm missing? These QObjects exist as QObjects strictly for the
ability to use the JavaScript bridging logic Qt provides... It does appear
to already delete direct the objects in some circumstances (reading
qobjectwrapper source).

Best Regards,
Andrew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20150929/0ac9bd68/attachment.html>


More information about the Interest mailing list