Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why qDeleteAll do not call clear on the container

Tags:

c++

qt

Reading the documentation of http://doc.qt.io/qt-4.8/qtalgorithms.html#qDeleteAll it requires us to call .clear on our container. Why is that?

Why qDeleteAll does not clear out container for us?

like image 648
Lorac Avatar asked Sep 06 '16 14:09

Lorac


2 Answers

As per Qt documents in http://doc.qt.io/qt-4.8/qtalgorithms.html#qDeleteAll

Notice that qDeleteAll() doesn't remove the items from the container; it merely calls delete on them.

I think decoupling qDeleteAll() from clear() can be useful in many situations, since it allows you to preserve the container attributes even after deleting the allocated memory for its items using qDeleteAll(). For example:

QHash<QString, int*> hash;
int * i1 = new int(10);
int * i2 = new int(20);

hash.insert("1", i1);
hash.insert("2", i2);

qDebug() << *hash["1"]; //10
qDebug() << hash.size(); //2

qDeleteAll(hash);

// qDeleteAll doesn't affect the hash keys nor size
qDebug() << hash.keys().at(0); //"1" 
qDebug() << hash.size(); //2

int * i3 = new int(100);
hash.insert(hash.keys().at(0), i3); // using the same key again

qDebug() << *hash["1"]; // 100

If you would use hash.clear() after qDeleteAll(hash), or if hash.clear() is called implicitly by qDeleteAll(hash), then you will not be able to retrieve the keys and the size in this example.

like image 167
HazemGomaa Avatar answered Oct 13 '22 14:10

HazemGomaa


One reason is that not every container will have the same method to clear itself. If you look at the code for qDeleteAll, it only has to increment between the iterators passed to it:

template <typename ForwardIterator>
Q_OUTOFLINE_TEMPLATE void qDeleteAll(ForwardIterator begin, ForwardIterator end)
{
    while (begin != end) {
        delete *begin;
        ++begin;
    }
}

Different containers could (although won't necessarily) have different methods to clear themselves, which this template doesn't need to know about in order to do its job.

like image 22
mike Avatar answered Oct 13 '22 13:10

mike