Search code examples
c++qtqt4qlist

Element is removed from QList but static counter of existing objects doesn't decrease


I have question about removing element from QList.

"myclass.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;

"main.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;
}

After executing I get:

  • NList size before: 4
  • Number of nodes before removing: 5
  • NList size after: 0
  • Number of nodes after removing: 5

What's bothering me is the fact that number of node2D objects is still 5 instead of 1.

Of course it can be managed like this:

for (i = 0; i < Nlist->size(); i++)
{
    delete (*Nlist)[i];
}
Nlist->clear();

but shouldn't node2D objects be automatically deleted while Nlist->clear()?

Or does it only happen when there is parent-child relation?

Thanks in advance,

Pawel


Solution

  • but shouldn't node2D objects be automatically deleted while Nlist->clear()?

    Not at all. What if i want to use these objects somewhere else, which is the case mostly for me. Managing the objects pointed by the pointers you add to the list is your concern, not QList's. Managing the copies of these pointers is on the other hand, QList's concern.