Should non-QObject derived classes “always” be put on the stack?

后端 未结 2 796
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 02:18

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

相关标签:
2条回答
  • 2021-01-03 02:37

    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.

    0 讨论(0)
  • 2021-01-03 02:45

    QString, and many other Qt classes, use implicit data sharing. That implies that memory is generally allocated on the heap.

    0 讨论(0)
提交回复
热议问题