我对从 QList 中删除元素有疑问。
“我的班级.h”:
class node2D : public QObject
{
Q_OBJECT
public:
node2D(){++s_NCount;};
~node2D(){--s_NCount;};
int checkCount(){return s_NCount;};
private:
static int s_NCount;
};
“myclass.cpp”:
int node2D::s_NCount = 0;
“主.cpp”:
void main()
{
int i,max_el(4);
QList<node2D*> *Nlist;
Nlist = new QList<node2D*>;
node2D controlNode;
for (i = 0 ;i < max_el ; i++)
{
Nlist->append(new node2D);
}
cout << "Nlist size before: " << Nlist->size() << endl;
cout << "Number of nodes before removing: " << controlNode.checkCount() << endl;
Nlist->clear();
cout << "NList size after: " << Nlist->size() << endl;
delete Nlist;
cout << "Number of nodes after removing: " << controlNode.checkCount() << endl;
}
执行后我得到:
- 之前的 NList 大小:4
- 移除前的节点数:5
- 之后的 NList 大小:0
- 移除后节点数:5
困扰我的是 node2D 对象的数量仍然是 5 而不是 1。
当然也可以这样管理:
for (i = 0; i < Nlist->size(); i++)
{
delete (*Nlist)[i];
}
Nlist->clear();
但是不应该在 Nlist->clear() 时自动删除 node2D 对象吗?
还是只有在存在父子关系时才会发生?
提前致谢,
帕维尔