QPointer智能指针

QList > alist;
QList > blist;
 
QPointer w1=new QWidget;
QPointer w2=new QWidget;
QPointer w3=new QWidget;
 
alist.append(w1);
alist.append(w2);
alist.append(w3);
 
blist.append(w1);
blist.append(w2);
blist.append(w3);
 
foreach(QPointer w,alist)
{
  if(w)
  {
    qDebug() << "alist delete";
     delete w;
  }
}
 
foreach(QPointer w,blist)
{
  if(w)
  {
    qDebug() << "blist delete--";
    delete w;
  }
  else
  {
    qDebug() << "blist w is NULL--";
  }

输出:

Starting F:\exercise\build-untitled17-desktop4_8_5-Debug\debug\untitled17.exe...
alist delete 
alist delete 
alist delete 
blist w is NULL-- 
blist w is NULL-- 
blist w is NULL-- 
F:\exercise\build-untitled17-desktop4_8_5-Debug\debug\untitled17.exe exited with code 0
QPointer objPtr;
qDebug() << "objPtr.isNull() : " << objPtr.isNull();

objPtr = new QObject();    //创建一个对象
qDebug() << "objPtr.isNull() : " << objPtr.isNull();

delete objPtr;            //释放对象 
qDebug() << "objPtr.isNull() : " << objPtr.isNull();

输出:

objPtr.isNull() : true

objPtr.isNull() : false

objPtr.isNull() : true
1.定义QPointer对象时,指针会自动置为nullptr


2.当QObject或派生类对象被删除时,QPointer能自动把其内部的指针设为nullptr(无需手动对对象置为空)

 

你可能感兴趣的:(Qt学习资料)