Your question is not really about stack-based vs heap-based allocation, but about creating and destroying dialogs everytime they are show and closed vs reusing them. Indeed, your examples can be rewritten to use the opposite allocation strategy:
void parentObjectClass::onButtonClick(){
if(dialog->exec()){
// do something
}
delete dialog;
}
void parentObjectClass::onButtonClick(){
QDialog *dialog = new QDialog(this);
if(dialog->exec()){
// do something
}
delete dialog;
}
To copy to clipboard, switch view to plain text mode
// header
Class parentObjectClass{
//....
//...
};
// cpp
parentObjectClass::parentObjectClass() : dialog(this) {
}
void parentObjectClass::onButtonClick(){
dialog.setDialog(values);
if(dialog.exec()){
// do something
}
}
// header
Class parentObjectClass{
//....
QDialog dialog;
//...
};
// cpp
parentObjectClass::parentObjectClass() : dialog(this) {
}
void parentObjectClass::onButtonClick(){
dialog.setDialog(values);
if(dialog.exec()){
// do something
}
}
To copy to clipboard, switch view to plain text mode
(note that in the second snippet dialog is not necessarily allocated on the stack, it is just allocated in the same memory block as the parentObjectClass.)
Now, about your question. I have no strong opinion on the subject. Does it really have a noticeable impact on the performance of your program? One interesting thing to notice is that by reusing a dialog you preserve its state (position and size) while you need to explicitly store it and re-apply it if you use distinct instances.
Bookmarks