资源描述
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: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;
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 <string>
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 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
dynamically 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 setParent
for each instance created from the class.
一个惯例,并且也是推荐的方式是,将父对象作为一个参数传给构造函数,成为第一个缺省参数。
Listing 1-2. Inheriting QObject and accepting a parent
继承QObject并接受父对象
#include <QObject>
#include <string>
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 function
using the MyClass class dynamically without Qt.
下面我们看看变化。首先是不用Qt:
Listing 1-3. Dynamic memory without Qt
不用Qt使用动态内存
#include <iostream>
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 is
not a big issue when exiting from the main function (because most modern operating systems
free the 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 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 to 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 1-4. Dynamic memory with Qt
使用Qt的动态内存使用
#include <QtDebug>
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 different
memory situations, as shown in Figure 1-1. The parent is gray because it is allocated on the
stack and thus automatically 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 allocated 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编程习惯:主窗体的创建问题
题记: 要知道,并不是只有初学者才会犯错。(shiroki的至理名言)
最近发现了一些有意思的问题,值得memo一下。
先来看段代码:
源码打印?
1. #include <QApplication>
2. #include <QWebView>
3. #include <QUrl>
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. <form>
2. <select id="headertest">
3. <option>Item1</option>
4. <option>Item2</option>
5. <option>Item3</option>
6. </select>
7. </form>
这个html里使用了下拉选单。 如果你运行程序并点开该选单,之后退出程序你就会看到Aborted错误提示,并打印出错误信息:“QWidget: Must construct a QApplication before a QPaintDevice”。
Qt的动态内存回收问题(3)
既然提出的问题,当然也要给出解决的方案。 有两种可行的方法避免该错误。 一个当然是纠正一下编程习惯,对mw不要用new的方式创建,改在stack上创建,如下代码:
源码打印?
1. #include <QApplication>
2. #include <QWebView>
3. #include <QUrl>
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 <QApplication>
2. #include <QWebView>
3. #include <QUrl>
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 : 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 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:
bool
quitOnLastWindowClosed ()
void
setQuitOnLastWindowClosed ( 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 deliver
展开阅读全文