Important: Please read the Qt Code of Conduct -

Deleting object

  • Hi;

    How to delete a object that created by new like follows;

    var myObject;
    myObject = new test(); // or String
    delete myObject;

    This example occures exception.


  • @VeNToR
    I don't use QML, but I feel like throwing my hat into the ring! But assuming this example represents usage of plain JavaScript, you do not use delete against a newed object in the way you would expect in, say, C++.

    The JS delete statement only deletes an object's properties (hence your exception). You cannot delete an object: you have to allow JS to garbage collect them when there are no more references to the object.

    So in your case you can just do nothing and it will get gc-ed on scope exit, or you can just go myObject = null; beforehand if you wish (though it may well not make JS gc it any sooner).

  • @JonB Thank for quick reply. I convert to "test" object to function, and, I have to delete (in my opinion) cause of that it keeps many C++ object inside.

  • @VeNToR
    I'm afraid I don't know what you mean. If you are happy, that's fine, if you want to show your new code, I'll look at it.

  • @VeNToR as mentioned before, JavaScript delete operator is not directly related to new operator.

    Please refer to documentation for more details, as your issue seems not related to QML (Qt) itself.

  • Thanks all ! I am moving codes from js to c++. At this way an other problem, qml can not handle exception from c++ (QJSEngine::evaluate("throw error;").

Log in to reply