title: How does Qt delete objects ? And what is the best way to store QObjects?
body: <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>