I am a little confused on whether I should prefer to initialize my main widgets on the stack or on the heap. In "C++ GUI Programming with QT 4," main widgets are initialized on the stack. Before I say more, I will explain what I mean:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow mainWin;
mainWin.show();
return app.exec();
}
Now, perhaps this is simply because it is safer, perhaps it is because they don't want to confuse readers about memory allocation in QT. Leaving out any deletes on objects inheriting from QObject certainly does allow readers to "forget" memory-management with QT objects. But, my question is, should we prefer that method, or the following:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow* mainWin = new MainWindow;
mainWin->show();
int execReturn = app.exec();
delete mainWin;
return execReturn;
}
The main reason I bring this question is I normally prefer to follow a pattern with choosing heap vs stack:
- If the item is large - Heap
- If the item is long-term - Heap
- Otherwise - Stack
Now, I guess my question boils down to two questions:
- Is QWidget large to the point where I should fear stack-overflows?
- How large is the stack for the average application? When should I fear for overflowing the stack (Other than obviously recursive functions)?
I realize it is unlikely that QWidget itself causes a stack-overflow, but of course this will be on top of any other stack usage my application may have.
sizeof
to see how large the object is. There is no "average stack", it varies widely between applications, and the limits vary widely by platform. If you're worried, and since this one is easy to track and there is absolutely no performance aspect, just use the heap. – Upbearsizeof
is accurate. – Upbear