文档详情

Qt_动态内存管理

沈***
实名认证
店铺
DOC
149.50KB
约14页
文档ID:156745792
Qt_动态内存管理_第1页
1/14

Qt的动态内存回收问题(1)Qt的动态内存回收机制容易让人觉得困惑,而能够参考的相关资料又很少,不少都是对此一笔带过,或者给出错误的说明费了不少劲,了解到了一些皮毛email:wulinshuxue@1、一篇博文在这篇博文中,提到了Qt的窗口回收机制,复制了过来大家也可以去原网址看Qt: 释放窗口资源1. 对于使用指针,使用new创建的窗口,当然可以使用delete显示的释放其占用的资源:Widget *w = new Widget();delete w;2. 对于使用指针,使用new创建的窗口,还可以使用QWidget::setAttribute方法来当窗口关闭后自动释放其占用的资源,而不用户显示的去调用delete释放,此方法当然也会调用窗口的析构函数:Widget *w = new Widget();w->setAttribute(Qt::WA_DeleteOnClose); (在程序中测试过一次,该值默认值为false,需要通过setAttribute来置为true)这可以用于非模态对话框,因为非模态对话框如果是用指针形式创建,但是再接着delete的话,窗口就没了,如果不使用delete释放窗口占用的资源,又会赞成泄漏。

如果使用普通变量创建,同样的也因为变量作用域马上就结束而窗口也没了,另一种方法就是使用多线程,不过这个的代价大了点所以这种技术在创建非模态对话框上是非常典型的运用测试方式:在Widget中分配大量的内存,显示与关闭多个此类窗口,看看任务管理器里此程序的内存变化情况,是否真正的释放了占用的内存(当然释放了)在C++中使用new分配内存时,如array = new double[length],此时,给array的内存实际上并没有真正的分配,必须等到第一次使用这些内存后才会真正地为其分配物理内存,如:memset(array, 1, length * sizeof(double))又一篇博文:/*********************************************发表于:2010-11-15 19:32:20class MainWindow;构造函数中增加:setAttribute(Qt::WA_DeleteOnClose)以后,C/C++ codeMainWindow mainWindow;mainWindow.setGeometry(30,30,1024,768);mainWindow.show();当关闭mainWindow时候,会有异常。

改成:C/C++ code MainWindow* mainWindow = new MainWindow; mainWindow->setGeometry(30, 30, 1024, 768); mainWindow->show();这样才可以,原因就是前者定义在栈上,后者定义在堆上,所以当设置了WA_DeleteOnClose以后,调用MainWindow析构函数才不会异常抛出setAttribute(Qt::WA_DeleteOnClose) 什么原理,有没有人研究过源码?**********************************************************************************************/3. 窗口的内存管理交给父Widget:Widget *w = new Widget(parent);但这时,如果父Widget不结束,这个窗口的资源一直会占用着至于使用哪种技术来释放窗口的资源,要看具体的运用时,哪种方式更合适 2、一本书看到了《Foundations of Qt Development》,作者是Johan Thelin。

这本书很适合使用过C++,开始接触Qt的程序员阅读下面的内容摘自该书,有点涉嫌侵权Making C++ “Qt-er”Because this is a book on programming, you will start with some code right away (see Listing 1-1).让C++Qt化Listing 1-1. A simple C++ class  一个简单的C++类#include using std::string;class MyClass{public:MyClass( const string& text );const string& text() const;void setText( const string& text );int getLengthOfText() const;private:string m_text;};Let’s make this class more powerful by using Qt. Inheriting QtThe first Qt-specific adjustment you will make to the code is really simple: you will simply letyour class inherit the QObject class, which will make it easier to manage instances of the classdynamically by giving instances parents that are responsible for their deletion.第一个Qt化的调整相当简单,让你的类继承QObject类就行了。

这会使得对类的实例的动态管理更加简单因为可以通过给实例父对象,这样就由父对象来负责删除了it is common—and recommended—to pass the parent asan argument to the constructor as the first default argument to avoid having to type setParentfor each instance created from the class.一个惯例,并且也是推荐的方式是,将父对象作为一个参数传给构造函数,成为第一个缺省参数Listing 1-2. Inheriting QObject and accepting a parent继承QObject并接受父对象#include #include using std::string;class MyClass : public QObject{public:MyClass( const string& text, QObject *parent = 0 );...};Let’s look at the effects of the change, starting with Listing 1-3.It shows a main functionusing the MyClass class dynamically without Qt.下面我们看看变化。

首先是不用Qt:Listing 1-3. Dynamic memory without Qt不用Qt使用动态内存#include int main( int argc, char **argv ){MyClass *a, *b, *c;a = new MyClass( "foo" );b = new MyClass( "ba-a-ar" );c = new MyClass( "baz" );std::cout << a->text() << " (" << a->getLengthOfText() << ")" << std::endl;a->setText( b->text() );std::cout << a->text() << " (" << a->getLengthOfText() << ")" << std::endl;int result = a->getLengthOfText() - c->getLengthOfText();delete a;delete b;delete c;return result;}Each new call must be followed by a call to delete to avoid a memory leak. Although it isnot a big issue when exiting from the main function (because most modern operating systemsfree the memory when the application exits), the destructors are not called as expected. Inlocations other than loop-less main functions, a leak eventually leads to a system crash whenthe system runs out of free memory. Compare it with Listing 1-4, which uses a parent that isautomatically deleted when the main function exits. The parent is responsible for callingdelete for all children and—ta-da!—the memory is freed.每个new都必须伴随一个delete来防止内存泄露。

我们将这个例子和下一个比较下面的1-4中,使用了一个父对象当main函数结束时,父对象会被自动删除而这个父对象负责删除所有的孩子哒-哒!内存被释放了■Note In the code shown in Listing 1-4, the parent object is added to show the concept. In real life, itwould be an object performing some sort of task—for example, a QApplication object, or (in the case ofa dialog box or a window) the this pointer of the window class.注意,在下面的代码中,父对象是用来展示概念的在实际应用中,它会是一个运行某种任务的对象,比如,QApplication对象,或者window类的this指针  Listing 1-4. Dynamic memory with Qt使用Qt的动态内存使用#include int main( int argc, char **argv ){QObject parent;MyClass *a, *b, *c;a = new MyClass( "foo", &parent );b = new MyClass( "ba-a-ar", &parent );c = new MyClass( "baz", &parent );qDebug() << QString::fromStdString(a->text())<< " (" << a->getLengthOfText() << ")";a->setText( b->text() );qDebug() << QString::fromStdString(a->text())<< " (" << a->getLengthOfText() << ")";return a->getLengthOfText() - c->getLengthOfText();}It might look odd to have a parent object like this, but most Qt applications use a QApplication object to actas a parent.有这样一个父对象也许看起来有点怪怪的。

但是,大多Qt应用程序使用一个QApplication对象来作为父对象When comparing the code complexity in Listing 1-3 and Listing 1-4, look at the differentmemory situations, as shown in Figure 1-1. The parent is gray because it is allocated on thestack and thus automatically deleted, whereas the instances of MyClass are white because theyare on the heap and must be handled manually. Because you use the parent to keep track ofthe children, you trust the parent to delete them when it is being deleted. So you no longerhave to keep track of the dynamically allocated memory as long as the root object is on thestack (or if you keep track of it).由于父对象在栈空间里,所以就不用你来负责空间释放,这样,它的子对象占用的动态内存也就无需去手动释放了。

 Qt的动态内存回收问题(2)3、一篇博文[转]纠正你的Qt编程习惯:主窗体的创建问题发表于 2010年09月02日 19:49 分类: Qt 统计: 0评/482阅 3人收藏此文章, 收藏此文章(?)关键字: Qt原文纠正你的Qt编程习惯:主窗体的创建问题题记: 要知道,并不是只有初学者才会犯错shiroki的至理名言)最近发现了一些有意思的问题,值得memo一下先来看段代码:源码打印?1. #include   2. #include   3. #include   4. int main(int argc, char* argv[])  5. {  6.     QApplication a(argc, argv);  7.     QWebView* mw = new QWebView;  8.     mw->show();  9.     mw->load(QUrl("  10.     return a.exec();  11. }  大家看得出这段代码中的问题吗? (呵呵,不要告诉我是cuteqt不能访问哦~)这段代码ms十分标准, 非常符合笔者平时写Qt程序书写main函数的习惯, 孰料想竟然是个错误的习惯,而且问题很严重哦。

给个提示:在程序退出时会aborted如果还没想出来是什么问题,嘿嘿,没关系,看了下面的答案你就明白了在这段程序里QApplication实例创建在stack上,生命期是main的大括号内, 而mw则通过new创建在heap上, 在程序退出时才会被析构 换句话说,mw的生存期长于application的生存期…..这可是Qt编程的大忌, 因为在Qt中所有的Paint Device都必须要在有QApplication实例的情况下创建和使用 不过如果把这个程序写出来运行一下, 未必会出现我说的aborted的问题,  大多数代码类似的程序都能安全的运行(这也是为什么用了那么多年的Qt从来没有注意过这个问题, 并且养成了我错误的编程习惯  这里的trick在于application退出时mw已经被关闭, mw中的所有Paint Device一般都不会被访问到了, 所以这个错误隐藏在很深的阴暗角落, 偷偷地嘲笑我们呢!要想试验这个问题也很简单,把load的参数换成本地文件 test.html, 并把下面的内容写进test.html就能看到拉:源码打印?1.   2.   3.   4.   5.   6.   7.    这个html里使用了下拉选单。

如果你运行程序并点开该选单,之后退出程序你就会看到Aborted错误提示,并打印出错误信息:“QWidget: Must construct a QApplication before a QPaintDevice”Qt的动态内存回收问题(3)既然提出的问题,当然也要给出解决的方案 有两种可行的方法避免该错误 一个当然是纠正一下编程习惯,对mw不要用new的方式创建,改在stack上创建,如下代码:源码打印?1. #include   2. #include   3. #include   4. int main(int arg, char* argv[])  5. {  6.     QApplication a(argc, argv);  7.     QWebView mw;  8.     mw.show();  9.     mw.load(QUrl("  10.     return a.exec();  11. }  另外还可以用Qt提供的API解决此问题, 想办法让mw在application之前clean up, 那就是用WA_DeleteOnClose属性。

该属性标示窗体会在close时被析构, 这样就保证不会留存在application析构之后了, 是个很好的办法代码如下: 源码打印?1. #include   2. #include   3. #include   4. int main(int arg, char* argv[])  5. {  6.     QApplication a(argc, argv);  7.     QWebView* mw = new QWebView;  8.     mw->show();  9.     mw->setAttribute(Qt::WA_DeleteOnClose);10. // mw->setAttribute(Qt::WA_QuitOnClose);11.     mw->load(QUrl("  12.     return a.exec();  13. }  发现问题和解决问题是件很有乐趣的事情,大家不要把时间都浪费在猜测上,要多动手多思考才能进步!//======================================//Qt Jambi也存在类似的问题,如果以程序启动的代码块去启动QApplication,在程序运行过程中,一些资源回收会报出Null指针错误,这些错误,通过debug,最终都会指向QWidget这个类。

当把QApplication启动的执行程序移出main函数,问题迎刃而解要多注意细节Qt的动态内存回收问题(4)4、几个函数(1) void QApplication::setMainWidget ( QWidget * mainWidget ) [static]Sets the application's main widget to mainWidget.In most respects the main widget is like any other widget, except that if it is closed, the application exits. QApplication does not take ownership of the mainWidget, so if you create your main widget on the heap you must delete it yourself.You need not have a main widget; connecting lastWindowClosed() to quit() is an alternative.On X11, this function also resizes and moves the main widget according to the -geometrycommand-line option, so you should set the default geometry (using QWidget::setGeometry()) before calling setMainWidget().See also mainWidget(), exec(), and quit(). (2)int QApplication::exec () [static]Enters the main event loop and waits until exit() is called, then returns the value that was set toexit() (which is 0 if exit() is called via quit()).It is necessary to call this function to start event handling. The main event loop receives events from the window system and dispatches these to the application widgets.Generally, no user interaction can take place before calling exec(). As a special case, modal widgets like QMessageBox can be used before calling exec(), because modal widgets call exec() to start a local event loop.To make your application perform idle processing, i.e., executing a special function whenever there are no pending events, use a QTimer with 0 timeout. More advanced idle processing schemes can be achieved using processEvents().We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application's main() function. This is because, on some platforms the QApplication::exec() call may not return. For example, on the Windows platform, when the user logs off, the system terminates the process after Qt closes all top-level windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the main() function, after the QApplication::exec() call.See also quitOnLastWindowClosed, quit(), exit(), processEvents(), and QCoreApplication::exec().(3)quitOnLastWindowClosed : boolThis property holds whether the application implicitly quits when the last window is closed.The default is true.If this property is true, the applications quits when the last visible primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose attribute set is closed. By default this attribute is set for all widgets except for sub-windows. Refer to Qt::WindowType for a detailed list of Qt::Window objects.Access functions:boolquitOnLastWindowClosed ()voidsetQuitOnLastWindowClosed ( bool quit )See also quit() and QWidget::close().(4)void QObject::deleteLater () [slot]Schedules this object for deletion.The object will be deleted when control returns to the event loop. If the event loop is not running when this function is called (e.g. deleteLater() is called on an object before QCoreApplication::exec()), the object will be deleted once the event loop is started.Note that entering and leaving a new event loop (e.g., by opening a modal dialog) will not perform the deferred deletion; for the object to be deleted, the control must return to the event loop from which deleteLater() was called.Note: It is safe to call this function more than once; when the first deferred deletion event is delivered, any pending events for the object are removed from the event queue.See also destroyed() and QPointer. (5)void QCoreApplication::aboutToQuit () [signal]This signal is emitted when the application is about to quit the main event loop, e.g. when the event loop level drops to zero. This may happen either after a call to quit() from inside the application or when the users shuts down the entire desktop session.The signal is particularly useful if your application has to do some last-second cleanup. Note that no user interaction is possible in this state.See also quit().(6)void QWidget::closeEvent ( QCloseEvent * event ) [virtual protected]This event handler is called with the given event when Qt receives a window close request for a top-level widget from the window system.By default, the event is accepted and the widget is closed. You can reimplement this function to change the way the widget responds to window close requests. For example, you can prevent the window from closing by calling ignore() on all events.Main window applications typically use reimplementations of this function to check whether the user's work has been saved and ask for permission before closing. For example, the Application Example uses a helper function to determine whether or not to close the window: void MainWindow::closeEvent(QCloseEvent *event) { if (maybeSave()) { writeSettings(); event->accept(); } else { event->ignore(); } }See also event(), hide(), close(), QCloseEvent, and Application Example.(7)QObject::~QObject ()   [virtual]Destroys the object, deleting all its child objects.All signals to and from the object are automatically disconnected, and any pending posted events for the object are removed from the event queue. However, it is often safer to usedeleteLater() rather than deleting a QObject subclass directly.Warning: All child objects are deleted. If any of these objects are on the stack or global, sooner or later your program will crash. We do not recommend holding pointers to child objects from outside the parent. If you still do, the destroyed() signal gives you an opportunity to detect when an object is destroyed.Warning: Deleting a QObject while pending events are waiting to be delivered can cause a crash. You must not delete the QObject directly if it exists in a different thread than the one currently executing. Use deleteLater() instead, which will cause the event loop to delete the object after all pending events have been delivered to it.See also deleteLater().(8)枚举enum Qt::WidgetAttributet::WA_DeleteOnClose55Makes Qt delete this widget when the widget has accepted the close event (see QWidget::closeEvent()). Qt::WA_QuitOnClose76Makes Qt quit the application when the last widget with the attribute set has accepted closeEvent(). This behavior can be modified with theQApplication::quitOnLastWindowClosedproperty. By default this attribute is set for all widgets of type Qt::Window.Qt::Widget0x00000000This is the default type for QWidget. Widgets of this type are child widgets if they have a parent, and independent windows if they have no parent. See also Qt::Window and Qt::SubWindow.Qt::Window0x00000001Indicates that the widget is a window, usually with a window system frame and a title bar, irrespective of whether the widget has a parent or not. Note that it is not possible to unset this flag if the widget does not have a parent.Qt::Dialog0x00000002 | WindowIndicates that the widget is a window that should be decorated as a dialog (i.e., typically no maximize or minimize buttons in the title bar). This is the default type for QDialog. If you want to use it as a modal dialog, it should be launched from another window, or have a parent and used with theQWidget::windowModality property. If you make it modal, the dialog will prevent other top-level windows in the application from getting any input. We refer to a top-level window that has a parent as a secondary window.Zz QT子窗体占用系统资源的释放问题 收藏QT中当主窗体退出时,子窗体占用的系统资源将自动释放。

但是,如果主窗体退出前,连续打开关闭子窗体,那么子窗体占用的系统资源将越来越多,并不进行释放这点可以通过任务管理器对程序使用的内存大小变化进行观察得到为了能够使子窗体自动释放系统资源,需要在子窗体类中添加这样一句:this->setAttribute(Qt::WA_DeleteOnClose,true);来使子窗体退出时自动释放系统资源它其实是在子窗体的closeEvent()函数中对窗体资源进行了删除,可以理解为进行了delete this;操作但是我在重载了closeEvent()函数的窗体类的构造函数中添加了this->setAttribute(Qt::WA_DeleteOnClose,true);这样的语句并没有实现窗体占用的资源释放后来我在窗体的closeEvent()函数的最后添加了一句:delete this;就可以实现窗体资源的自动释放了当子窗体释放资源的时候,由于子窗体和其上的组件是父子关系,从而窗体上的组件占用的资源不需要我们手动释放,由子窗体自动释放总结:1)若要实现子窗体占用系统资源的释放,要在构造函数中添加this->setAttribute(Qt::WA_DeleteOnClose,true);2)若重载了closeEvent()函数,则需要在此函数的最后添加delete this;进行资源的释放。

 PS:以上是我的个人理解,如有不妥的地方,欢迎指正。

下载提示
相关文档
正为您匹配相似的精品文档