qt - C++ - Why do I create these widgets on the heap? -
when creating gui c++ , qt can create label example :
qlabel* label = new qlabel("hey you!", centralwidgetparent);
this creates object on heap , stay there until either delete manually or parent gets destroyed. question why need pointer that? why not create on stack?
//create member variable of class mainwindow qlabel label; //set parent show , give text user can see qwidget* centralwidget = new qwidget(this); //needed add widgets window this->setcentralwidget( centralwidget ); label.setparent(centralwidget); label.settext( "haha" );
this works fine, can see label , did not vanish.
we use pointers in c++ let live longer can use object in various scopes. when create member variable, won't stay until object gets destroyed?
edit: maybe didn't clarify enough. mainwindow class:
class mainwindow : public qmainwindow { q_object qlabel label; //first introduced here... public: mainwindow(qwidget *parent = 0); ~mainwindow(); }; //constructor mainwindow::mainwindow(qwidget *parent) : qmainwindow(parent) { qwidget* centralwidget = new qwidget(this); this->setcentralwidget( centralwidget ); label.setparent(centralwidget); label.settext( "haha" ); }
if label
gets out of scope, destructor (qlabel::~qlabel
) called. docs:
destroys object, deleting child objects.
it not necessary create object on heap - put object on stack, need responsible lifetime of object (the 1 of problematic issues allocating data on heap question of "who , when should delete these objects?", , in qt handled hierarchy - whenever delete widget, child widgets deleted).
why program works - don't know - may not work (label
destroyed @ end of scope). issue - how change text of label
(from slot, example) if don't have reference it?
edit saw label
member of mainwindow
. fine have complete objects, , not pointer objects member of class, not destroyed before mainwindow
is. please note if create instance of mainwindow
this:
mainwindow *w = new mainwindow();
label
created on heap.
Comments
Post a Comment