ImageVerifierCode 换一换
格式:DOC , 页数:14 ,大小:149.50KB ,
资源ID:7784222      下载积分:10 金币
快捷注册下载
登录下载
邮箱/手机:
温馨提示:
快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。 如填写123,账号就是123,密码也是123。
特别说明:
请自助下载,系统不会自动发送文件的哦; 如果您已付费,想二次下载,请登录后访问:我的下载记录
支付方式: 支付宝    微信支付   
验证码:   换一换

开通VIP
 

温馨提示:由于个人手机设置不同,如果发现不能下载,请复制以下地址【https://www.zixin.com.cn/docdown/7784222.html】到电脑端继续下载(重复下载【60天内】不扣币)。

已注册用户请登录:
账号:
密码:
验证码:   换一换
  忘记密码?
三方登录: 微信登录   QQ登录  

开通VIP折扣优惠下载文档

            查看会员权益                  [ 下载后找不到文档?]

填表反馈(24小时):  下载求助     关注领币    退款申请

开具发票请登录PC端进行申请

   平台协调中心        【在线客服】        免费申请共赢上传

权利声明

1、咨信平台为文档C2C交易模式,即用户上传的文档直接被用户下载,收益归上传人(含作者)所有;本站仅是提供信息存储空间和展示预览,仅对用户上传内容的表现方式做保护处理,对上载内容不做任何修改或编辑。所展示的作品文档包括内容和图片全部来源于网络用户和作者上传投稿,我们不确定上传用户享有完全著作权,根据《信息网络传播权保护条例》,如果侵犯了您的版权、权益或隐私,请联系我们,核实后会尽快下架及时删除,并可随时和客服了解处理情况,尊重保护知识产权我们共同努力。
2、文档的总页数、文档格式和文档大小以系统显示为准(内容中显示的页数不一定正确),网站客服只以系统显示的页数、文件格式、文档大小作为仲裁依据,个别因单元格分列造成显示页码不一将协商解决,平台无法对文档的真实性、完整性、权威性、准确性、专业性及其观点立场做任何保证或承诺,下载前须认真查看,确认无误后再购买,务必慎重购买;若有违法违纪将进行移交司法处理,若涉侵权平台将进行基本处罚并下架。
3、本站所有内容均由用户上传,付费前请自行鉴别,如您付费,意味着您已接受本站规则且自行承担风险,本站不进行额外附加服务,虚拟产品一经售出概不退款(未进行购买下载可退充值款),文档一经付费(服务费)、不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
4、如你看到网页展示的文档有www.zixin.com.cn水印,是因预览和防盗链等技术需要对页面进行转换压缩成图而已,我们并不对上传的文档进行任何编辑或修改,文档下载后都不会有水印标识(原文档上传前个别存留的除外),下载后原文更清晰;试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓;PPT和DOC文档可被视为“模板”,允许上传人保留章节、目录结构的情况下删减部份的内容;PDF文档不管是原文档转换或图片扫描而得,本站不作要求视为允许,下载前可先查看【教您几个在下载文档中可以更好的避免被坑】。
5、本文档所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用;网站提供的党政主题相关内容(国旗、国徽、党徽--等)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
6、文档遇到问题,请及时联系平台进行协调解决,联系【微信客服】、【QQ客服】,若有其他问题请点击或扫码反馈【服务填表】;文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“【版权申诉】”,意见反馈和侵权处理邮箱:1219186828@qq.com;也可以拔打客服电话:0574-28810668;投诉电话:18658249818。

注意事项

本文(Qt_动态内存管理.doc)为本站上传会员【pc****0】主动上传,咨信网仅是提供信息存储空间和展示预览,仅对用户上传内容的表现方式做保护处理,对上载内容不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知咨信网(发送邮件至1219186828@qq.com、拔打电话4009-655-100或【 微信客服】、【 QQ客服】),核实后会尽快下架及时删除,并可随时和客服了解处理情况,尊重保护知识产权我们共同努力。
温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载【60天内】不扣币。 服务填表

Qt_动态内存管理.doc

1、Qt的动态内存回收问题(1) Qt的动态内存回收机制容易让人觉得困惑,而能够参考的相关资料又很少,不少都是对此一笔带过,或者给出错误的说明。费了不少劲,了解到了一些皮毛。 email:wulinshuxue@ 1、一篇博文 在这篇博文中,提到了Qt的窗口回收机制,复制了过来。大家也可以去原网址看。 Qt: 释放窗口资源 1. 对于使用指针,使用new创建的窗口,当然可以使用delete显示的释放其占用的资源: Widget *w = new Widget(); delete w; 2. 对于使用指针,使用new创建的窗口,还可以使用QWidget::setAttr

2、ibute方法来当窗口关闭后自动释放其占用的资源,而不用户显示的去调用delete释放,此方法当然也会调用窗口的析构函数: Widget *w = new Widget(); w->setAttribute(Qt::WA_DeleteOnClose); (在程序中测试过一次,该值默认值为false,需要通过setAttribute来置为true) 这可以用于非模态对话框,因为非模态对话框如果是用指针形式创建,但是再接着delete的话,窗口就没了,如果不使用delete释放窗口占用的资源,又会赞成泄漏。如果使用普通变量创建,同样的也因为变量作用域马上就结束而窗口也没了,另一种方法就是使用

3、多线程,不过这个的代价大了点。所以这种技术在创建非模态对话框上是非常典型的运用。 测试方式:在Widget中分配大量的内存,显示与关闭多个此类窗口,看看任务管理器里此程序的内存变化情况,是否真正的释放了占用的内存(当然释放了)。在C++中使用new分配内存时,如array = new double[length],此时,给array的内存实际上并没有真正的分配,必须等到第一次使用这些内存后才会真正地为其分配物理内存,如:memset(array, 1, length * sizeof(double)) 又一篇博文: /*********************************

4、 发表于:2010-11-15 19:32:20 class MainWindow;构造函数中增加:setAttribute(Qt::WA_DeleteOnClose)以后, C/C++ code MainWindow mainWindow; mainWindow.setGeometry(30,30,1024,768); mainWindow.show(); 当关闭mainWindow时候,会有异常。改成: C/C++ code MainWindow* mainWindow = new MainWindow;

5、 mainWindow->setGeometry(30, 30, 1024, 768); mainWindow->show(); 这样才可以,原因就是前者定义在栈上,后者定义在堆上,所以当设置了WA_DeleteOnClose以后,调用MainWindow析构函数才不会异常抛出。 setAttribute(Qt::WA_DeleteOnClose) 什么原理,有没有人研究过源码? **********************************************************************************************/

6、 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 wil

7、l 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

8、 private: string m_text; }; Let’s make this class more powerful by using Qt. Inheriting Qt The first Qt-specific adjustment you will make to the code is really simple: you will simply let your class inherit the QObject class, which will make it easier to manage instances of the class dyn

9、amically by giving instances parents that are responsible for their deletion. 第一个Qt化的调整相当简单,让你的类继承QObject类就行了。这会使得对类的实例的动态管理更加简单。因为可以通过给实例父对象,这样就由父对象来负责删除了。 it is common—and recommended—to pass the parent as an argument to the constructor as the first default argument to avoid having to type se

10、tParent for 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

11、 QObject *parent = 0 ); ... }; Let’s look at the effects of the change, starting with Listing 1-3.It shows a main function using the MyClass class dynamically without Qt. 下面我们看看变化。首先是不用Qt: Listing 1-3. Dynamic memory without Qt 不用Qt使用动态内存 #include int main( int argc, char **

12、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

13、 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 is not a big issue when exiting from the main function (because most modern operating systems free the

14、memory when the application exits), the destructors are not called as expected. In locations other than loop-less main functions, a leak eventually leads to a system crash when the system runs out of free memory. Compare it with Listing 1-4, which uses a parent that is automatically deleted when

15、the main function exits. The parent is responsible for calling delete 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 t

16、o show the concept. In real life, it would be an object performing some sort of task—for example, a QApplication object, or (in the case of a dialog box or a window) the this pointer of the window class. 注意,在下面的代码中,父对象是用来展示概念的。在实际应用中,它会是一个运行某种任务的对象,比如,QApplication对象,或者window类的this指针。    Listing

17、 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()) <<

18、 " (" << 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 QAppl

19、ication object to actas a parent. 有这样一个父对象也许看起来有点怪怪的。但是,大多Qt应用程序使用一个QApplication对象来作为父对象。 When comparing the code complexity in Listing 1-3 and Listing 1-4, look at the different memory situations, as shown in Figure 1-1. The parent is gray because it is allocated on the stack and thus automatic

20、ally deleted, whereas the instances of MyClass are white because they are on the heap and must be handled manually. Because you use the parent to keep track of the children, you trust the parent to delete them when it is being deleted. So you no longer have to keep track of the dynamically alloca

21、ted memory as long as the root object is on the stack (or if you keep track of it). 由于父对象在栈空间里,所以就不用你来负责空间释放,这样,它的子对象占用的动态内存也就无需去手动释放了。   Qt的动态内存回收问题(2) 3、一篇博文 [转]纠正你的Qt编程习惯:主窗体的创建问题 发表于 2010年09月02日 19:49 分类: Qt 统计: 0评/482阅 3人收藏此文章, 收藏此文章(?) 关键字: Qt 原文纠正你的Qt编程习惯:主窗体的创建问题 题记: 要知道,并不

22、是只有初学者才会犯错。(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.     m

23、w->load(QUrl("   10.     return a.exec();   11. }   大家看得出这段代码中的问题吗? (呵呵,不要告诉我是cuteqt不能访问哦~) 这段代码ms十分标准, 非常符合笔者平时写Qt程序书写main函数的习惯, 孰料想竟然是个错误的习惯,而且问题很严重哦。 给个提示:在程序退出时会aborted。 如果还没想出来是什么问题,嘿嘿,没关系,看了下面的答案你就明白了。 在这段程序里QApplication实例创建在stack上,生命期是main的大括号内, 而mw则通过new创建在heap上, 在程序退出时才会被析构。 换句话说,mw的生

24、存期长于application的生存期…..这可是Qt编程的大忌, 因为在Qt中所有的Paint Device都必须要在有QApplication实例的情况下创建和使用。 不过如果把这个程序写出来运行一下, 未必会出现我说的aborted的问题,  大多数代码类似的程序都能安全的运行(这也是为什么用了那么多年的Qt从来没有注意过这个问题, 并且养成了我错误的编程习惯。)。  这里的trick在于application退出时mw已经被关闭, mw中的所有Paint Device一般都不会被访问到了, 所以这个错误隐藏在很深的阴暗角落, 偷偷地嘲笑我们呢! 要想试验这个问题也很简单,把load的

25、参数换成本地文件 test.html, 并把下面的内容写进test.html就能看到拉: 源码打印? 1.

   2.    3.    4.    5.    6.    7.      这个html里使用了下拉选单。 如果你运行程序并点开该选单,之后退出程序你就会看到Aborted错误提示,并打印出错误信息:“QWidget: Must constr

26、uct 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(ar

27、gc, 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   

28、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->l

29、oad(QUrl("   12.     return a.exec();   13. }   发现问题和解决问题是件很有乐趣的事情,大家不要把时间都浪费在猜测上,要多动手多思考才能进步! //======================================// Qt Jambi也存在类似的问题,如果以程序启动的代码块去启动QApplication,在程序运行过程中,一些资源回收会报出Null指针错误,这些错误,通过debug,最终都会指向QWidget这个类。当把QApplication启动的执行程序移出main函数,问题迎刃而解。要多注意细节。 Qt的动态内存回收问

30、题(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 main

31、Widget, 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 s

32、et 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 exi

33、t() 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 widget

34、s 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

35、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,

36、 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 quitOnLastWindo

37、wClosed, quit(), exit(), processEvents(), and QCoreApplication::exec(). (3) quitOnLastWindowClosed : bool This 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 prim

38、ary 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: bool quitOnLastWindowClosed () void setQuitO

39、nLastWindowClosed ( 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()

40、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

41、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::aboutTo

42、Quit () [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 particul

43、arly 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

44、 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

45、 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::c

46、loseEvent(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 obje

47、ct, 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

48、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. Wa

49、rning: 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 deliver

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2026 宁波自信网络信息技术有限公司  版权所有

客服电话:0574-28810668  投诉电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服