Wagmare
Wagmare

Reputation: 1406

how to avoid memory leak in dynamically allocated widget

I have to show a widgetA in a mainwindow without making it as a child of mainwindow . so if i dynamically allocate the memory space, it will trend to leak memory

Widget *wid = new Widget;
wid->show();

so i want to know how elegantly handle dynamic memory allocation of a widget without leaking.

Upvotes: 2

Views: 306

Answers (2)

Dmitry Sazonov
Dmitry Sazonov

Reputation: 8994

You may set mainwindow as a parent and turn on Qt::Window flag. This is the "Qt way".

Upvotes: 1

user4842163
user4842163

Reputation:

QT is rather old school C++, so many of its examples just use raw pointers and manual calls to delete without conforming to RAII. This can kind of work well enough in practice since most of your QObjects can often be transferred ownership to a RAII-conforming container quite quickly with the exception of a few and because Qt hardly throws exceptions.

However, it does provide its own smart pointers like this:

http://doc.qt.digia.com/4.6/qscopedpointer.html

QScopedPointer<Widget> wid(new Widget);
wid->show();
// `wid` will automatically call `delete` when it goes out of scope.

Since you often need to transfer ownership to do things like insert child widgets to a layout, the take method becomes handy here which is basically equivalent to the release method of std::unique_ptr.

I would suggest just sticking to the standard C++ smart pointers like unique_ptr, in which case you can do this:

unique_ptr<Widget> wid(new Widget);
wid->show();

... but it's up to you whether you want to go deeper into QT or stay closer to the realm of the C++ standard.

Upvotes: 5

Related Questions