Coming from the Symbian world, I\'m used to using the heap as much as possible to avoid running out of stack space, especially when handling descriptors. CBase derived class
As sje397 said: It's idiomatic to put QString
and containers on the stack, as they are implicitly shared. Their internals (pimpl idiom "d" pointer) are created on the heap. There is no point in creating the object itself on the heap, too. Just causes memory-management hassles and you lose the intended copy-on-write properties when passing pointers to strings/containers around.
QObjects
on the other hand you want to create on the heap in almost all cases, as otherwise they would be destructed again right away. They can't be copied or assigned (well, one can enforce it for own subclasses, but the QObject
semantics are broken then), and usually they are supposed to survive the method body they are created in.
Exception is QDialog
, which is often created on the stack, followed by QDialog::exec
, which blocks until the dialog is closed. But even that is strictly spoken unsafe, as external events (RPC calls, background operations) could cause the dialog to be deleted by its parent (if the parent itself is deleted) before exec returns.
Then having the dialog created on the stack will cause double deletion when unwinding the stack -> crash.
QString, and many other Qt classes, use implicit data sharing. That implies that memory is generally allocated on the heap.