2014年03月13日 星期四 09:35
在现代的C++语言中,我们极力避免使用普通的指针,所以会出现各种“智能”的指针,这些指针的目的基本都是简化内存管理的工作,避免内存泄露和悬空指针的问题。
在Qt中,QPointer的特点是:当其指向的对象销毁之后,将自动指向0地址,这样就可以避免悬空指针的问题。
QScopedPointer的特点可以顾名思义,当离开指针的有效范围后,指针所指向的对象自动销毁,这就避免了内存泄露的问题。
当然,上述两个都尤其局限性,C++ 11引入了shared_ptr,我认为,这个更加智能一些。
示例代码如下:
#include <QCoreApplication>
#include <QtCore>
QByteArray file_get_contents(QString file){
/*
* QScopedPointer guarantees that the object
* pointed to will get deleted when the current
* scope disappears.
*/
QScopedPointer<QFile> f(new QFile(file));
f->open(QIODevice::ReadOnly);
return f->readAll();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile *f=new QFile();
/* A guarded pointer, QPointer<T>,
* behaves like a normal C++ pointer T *,
* except that it is automatically set to 0
* when the referenced object is destroyed
* */
QPointer<QFile> pf=f;
qDebug() << f;
qDebug() << pf;
delete f;
qDebug() << (f == 0);
qDebug() << (pf == 0);
qDebug() << file_get_contents("D:/cpp/test.txt");
return a.exec();
}
参考资料:
http://qt-project.org/doc/qt-5/QPointer.html
Zeuux © 2025
京ICP备05028076号