問題描述
聽說widget應該在堆上分配(使用new),然后就不需要刪除了(自動完成).
- 有人能解釋一下原因嗎?
- 如果小部件不是以這種方式分配而是在堆棧中,會發生什么情況?
我不確定這是否重要,但我創建的所有小部件都有一個父級.
這個說:
<塊引用>如果 parent 為 0,則新小部件變為一個窗口.如果 parent 是另一個小部件,這個小部件成為一個子窗口內父.新的小部件是刪除其父項時刪除.
沒有魔法.簡單地說,一個 QObject 會在它的析構函數中自動刪除它的孩子.所以,只要你的小部件有一個父級并且你銷毀了那個父級,你就不必擔心子級.因此,如果您想知道 QObject * parent
參數是什么,那么,這就是它的用途.
此外,來自文檔:
<塊引用><塊引用>刪除所有子對象.如果這些對象中的任何一個在堆棧上或全局上,您的程序遲早會崩潰.
因此,避免將父級分配給堆棧分配的對象.
I heard that the widgets should be allocated on the heap (using new), and then there are no needs to delete them (it is done automatically).
- Can someone explain why?
- What happens if a widget is not allocated that way, but on a stack?
I am not sure if it matters, but all widgets I am creating have a parent.
This says :
If parent is 0, the new widget becomes a window. If parent is another widget, this widget becomes a child window inside parent. The new widget is deleted when its parent is deleted.
There's no magic involved. Simply put, a QObject automatically deletes its children in its destructor. So, as long as your widget has a parent and that you destroy that parent, you don't have to worry about the children. So if you wondered what was that QObject * parent
parameter, well, that's what it's there for.
Also, from the doc:
All child objects are deleted. If any of these objects are on the stack or global, sooner or later your program will crash.
So, avoid giving parents to objects that are stack-allocated.
這篇關于創建和釋放 Qt 小部件對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!