Question

I have a class SomeObjectList : public QList<SomeObject*>

I am creating pointers to SomeObject and sticking them in the list like so:

SomeObjectList MyClass::getSomeObjects()
{
    SomeObjectList list;

    for( int i=0; i<10; ++i )
    {
        list << new SomeObject();
    }

    return list;   // Crashes approximately here in QList::~QList
}

I'm getting a crash in the QList destructor, and it looks like free() may be being called. I found the source code for the function (Qt 4.8.2) and it looks like this:

template <typename T>
Q_OUTOFLINE_TEMPLATE QList<T>::~QList()
{
    if (!d->ref.deref())
        free(d);
}

Does this mean that free() is being called on any pointers left in the list when the destructor is called? I have used lists in other places without this problem. Under what circumstances does the destructor call free()?

Was it helpful?

Solution

To elaborate: destroying a QList will destroy the elements of the list. If the elements are pointers, the pointers themselves are destroyed, not the pointees. You can use qDeleteAll to delete the pointees.

(That will use operator delete, which is the right choice if and only if you're using operator new; malloc will always require free and operator new[] will always require operator delete[]).

That having been said, returning a QList by value won't destroy it, as its refcount won't drop to 0. Getting a crash there means it's very likely that you have some memory corruption. Use valgrind or similar tools to debug that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top