Note that there are some explanatory texts on larger screens.

plurals
  1. POHow does Qt delete objects ? And what is the best way to store QObjects?
    primarykey
    data
    text
    <p>I heard that objects in Qt will automatically delete their children, I want to know what will happen in those situations.</p> <pre><code>#include &lt;QApplication&gt; #include &lt;QLabel&gt; #include &lt;QHBoxLayout&gt; #include &lt;QWidget&gt; int main(int argc, char **argv) { QApplication app(argc, argv); /* QLabel label("label"); // Program will crash. Destruct order is 1. widget, 2. layout, 3. label QHBoxLayout layout; // But layout will be deleted twice QWidget widget; */ QWidget widget; // Program doesn't seem to crash but is it safe ? Does Qt use QHBoxLayout layout; // delete to operate on already destructed children ? QLabel label("label"); layout.addWidget(&amp;label); // layout is label's parent widget.setLayout(&amp;layout); // widget is layout's parent widget.show(); return app.exec(); } </code></pre> <p>Is this allowed in Qt? What does Qt do when destroying a child ?</p> <p>BTW, I considered using smart pointers such as shared_ptr. But I think Qt would also delete the object which had already been destroyed by smart pointer too.</p> <p>I know you would like to use new to allocate dynamic memory for objects. But I don't feel its reassuring, please tell me if there are any situations (e.g. exceptions) that will lead to memory leaks when relying on Qt's object tree to handle dynamic memory?</p> <p>If I use objects rather than pointers to dynamically allocate objects, I have to consider the order of destruction of objects as long as they have ownership, which is tedious. I don't know whether it is good practice to use dynamic memory in Qt. </p> <p>Do you have any suggestions or better solutions?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload