C++ - Why do I create these widgets on the heap?

前端 未结 5 2151
有刺的猬
有刺的猬 2020-12-31 17:43

When creating a GUI with C++ and Qt you can create a label for example like this :

QLabel* label = new QLabel(\"Hey you!\", centralWidgetParent);
         


        
5条回答
  •  庸人自扰
    2020-12-31 18:19

    If your label gets out of the scope, the destructor (QLabel::~QLabel) will be called. From the docs:

    Destroys the object, deleting all its child objects.

    It is not necessary to create object on the heap - you could put the object on the stack, but then you need to be responsible about lifetime of the object (the one of the most problematic issues about allocating data on the heap is the question of "who and when should delete these objects?", and in Qt it is handled by the hierarchy - whenever you delete your widget, all the child widgets will be deleted).

    Why your program works - I don't know - it may just not work (label is destroyed at the end of the scope). Another issue is - how will you change the text of the label (from some slot, for example) if you don't have a reference to it?

    Edit I just saw that your label is a member of the MainWindow. It is perfectly fine to have a complete objects, and not the pointer to the objects as the member of your class, as it will not be destroyed before MainWindow is. Please note that if you create instance of your MainWindow like this:

    MainWindow *w = new MainWindow();
    

    label will be created on the heap.

提交回复
热议问题